robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
359459dec6
master
1#include <assert.h> 2#include <limits.h> 3#include <stdbool.h> 4#include <stdint.h> 5#include <stdio.h> 6#include <string.h> 7#include <uv.h> 8 9#include "nvim/api/private/defs.h" 10#include "nvim/ascii_defs.h" 11#include "nvim/autocmd.h" 12#include "nvim/autocmd_defs.h" 13#include "nvim/buffer_defs.h" 14#include "nvim/eval.h" 15#include "nvim/eval/typval_defs.h" 16#include "nvim/eval/vars.h" 17#include "nvim/eval_defs.h" 18#include "nvim/event/loop.h" 19#include "nvim/event/multiqueue.h" 20#include "nvim/globals.h" 21#include "nvim/input.h" 22#include "nvim/insexpand.h" 23#include "nvim/keycodes.h" 24#include "nvim/log.h" 25#include "nvim/macros_defs.h" 26#include "nvim/main.h" 27#include "nvim/mouse.h" 28#include "nvim/msgpack_rpc/channel.h" 29#include "nvim/option_vars.h" 30#include "nvim/os/input.h" 31#include "nvim/os/os_defs.h" 32#include "nvim/os/time.h" 33#include "nvim/profile.h" 34#include "nvim/state.h" 35#include "nvim/state_defs.h" 36#include "nvim/types_defs.h" 37 38#define READ_BUFFER_SIZE 0xfff 39#define INPUT_BUFFER_SIZE ((READ_BUFFER_SIZE * 4) + MAX_KEY_CODE_LEN) 40 41static char input_buffer [INPUT_BUFFER_SIZE ]; 42static char * input_read_pos = input_buffer ; 43static char * input_write_pos = input_buffer ; 44 45static bool blocking = false; 46static int cursorhold_time = 0 ;///< time waiting for CursorHold event 47static int cursorhold_tb_change_cnt = 0 ;///< tb_change_cnt when waiting started 48 49#include "os/input.c.generated.h" 50 51static void cursorhold_event (void ** argv ) 52{ 53event_T event = State & MODE_INSERT ?EVENT_CURSORHOLDI :EVENT_CURSORHOLD ; 54apply_autocmds (event ,NULL ,NULL , false,curbuf ); 55did_cursorhold = true; 56} 57 58static void create_cursorhold_event (bool events_enabled ) 59{ 60// If events are enabled and the queue has any items, this function should not 61// have been called (`inbuf_poll` would return true). 62// TODO(tarruda): Cursorhold should be implemented as a timer set during the 63// `state_check` callback for the states where it can be triggered. 64assert (!events_enabled || multiqueue_empty (main_loop .events )); 65multiqueue_put (main_loop .events ,cursorhold_event ,NULL ); 66} 67 68static void reset_cursorhold_wait (int tb_change_cnt ) 69{ 70cursorhold_time = 0 ; 71cursorhold_tb_change_cnt = tb_change_cnt ; 72} 73 74/// Reads OS input into `buf`, and consumes pending events while waiting (if `ms != 0`). 75/// 76/// - Consumes available input received from the OS. 77/// - Consumes pending events. 78/// - Manages CursorHold events. 79/// - Handles EOF conditions. 80/// 81/// Originally based on the Vim `mch_inchar` function. 82/// 83/// @param buf Buffer to store consumed input. 84/// @param maxlen Maximum bytes to read into `buf`, or 0 to skip reading. 85/// @param ms Timeout in milliseconds. -1 for indefinite wait, 0 for no wait. 86/// @param tb_change_cnt Used to detect when typeahead changes. 87/// @param events (optional) Events to process. 88/// @return Bytes read into buf, or 0 if no input was read 89int input_get (uint8_t * buf ,int maxlen ,int ms ,int tb_change_cnt ,MultiQueue * events ) 90{ 91assert ((maxlen > 0 && buf != NULL )|| maxlen == 0 ); 92// This check is needed so that feeding typeahead from RPC can prevent CursorHold. 93if (tb_change_cnt != cursorhold_tb_change_cnt ) { 94reset_cursorhold_wait (tb_change_cnt ); 95 } 96 97#define TRY_READ () \ 98 do { \ 99 if (maxlen && input_available()) { \ 100 reset_cursorhold_wait(tb_change_cnt); \ 101 size_t to_read = MIN((size_t)maxlen, input_available()); \ 102 memcpy(buf, input_read_pos, to_read); \ 103 input_read_pos += to_read; \ 104/* This is safe because INPUT_BUFFER_SIZE fits in an int. */ \ 105assert (to_read <=INT_MAX ); \ 106return (int )to_read ; \ 107 } \ 108 }while (0 ) 109 110TRY_READ (); 111 112// No risk of a UI flood, so disable CTRL-C "interrupt" behavior if it's mapped. 113if ((mapped_ctrl_c |curbuf -> b_mapped_ctrl_c )& get_real_state ()) { 114ctrl_c_interrupts = false; 115 } 116 117if (ms >=0 ) { 118if (!inbuf_poll (ms ,events )) { 119return 0 ; 120 } 121 }else { 122uint64_t wait_start = os_hrtime (); 123cursorhold_time = MIN (cursorhold_time , (int )p_ut ); 124// When an autocomplete is pending, wake at the sooner of 125// 'autocompletedelay' and 'updatetime' so the delay does not postpone 126// CursorHold. Once CursorHold has fired, only the delay is left. 127// Gate the injection like trigger_cursorhold() so the deferred key 128// cannot fire while outside Insert mode, but do still fire the key 129// when recording a register (gotchars_add_byte() will ignore it). 130bool delay_pending = ins_compl_autocomplete_pending ()&& p_acl > 0 131&& typebuf .tb_len == 0 132&& !ins_compl_active () 133&& (get_real_state ()& MODE_INSERT )!= 0 ; 134// Measure the delay from when it was armed (the keystroke), so a 135// CursorHold returning in between does not push the popup back. 136int64_t wait_time = p_ut - cursorhold_time ; 137if (delay_pending ) { 138int64_t delay_left = p_acl - ins_compl_autocomplete_elapsed (); 139wait_time = MIN (MAX (delay_left ,0 ),wait_time ); 140 } 141if (!inbuf_poll ((int )wait_time ,events )) { 142if (silent_mode ) { 143// Ran out of input: exit silent/batch-mode (-es/-Es). 144getout (0 ); 145 } 146// The 'autocompletedelay' expired: trigger the popup. When 147// 'updatetime' is shorter, fall through to CursorHold instead. 148if (delay_pending && ins_compl_autocomplete_elapsed () >=p_acl 149&& (buf == NULL || maxlen >=3 )&& !typebuf_changed (tb_change_cnt )) { 150if (buf == NULL ) { 151uint8_t ibuf [3 ]; 152ibuf [0 ]= K_SPECIAL ; 153ibuf [1 ]= KS_EXTRA ; 154ibuf [2 ]= KE_COMPLETE_DELAY ; 155input_enqueue_raw ((char * )ibuf ,3 ); 156return 0 ; 157 } 158buf [0 ]= K_SPECIAL ; 159buf [1 ]= KS_EXTRA ; 160buf [2 ]= KE_COMPLETE_DELAY ; 161return 3 ; 162 } 163reset_cursorhold_wait (tb_change_cnt ); 164if (trigger_cursorhold ()&& !typebuf_changed (tb_change_cnt )) { 165create_cursorhold_event (events == main_loop .events ); 166 }else { 167before_blocking (); 168inbuf_poll (-1 ,events ); 169 } 170 }else { 171cursorhold_time += (int )((os_hrtime ()- wait_start ) /1000000 ); 172 } 173 } 174 175ctrl_c_interrupts = true; 176 177// If input was put directly in typeahead buffer bail out here. 178if (typebuf_changed (tb_change_cnt )) { 179return 0 ; 180 } 181 182TRY_READ (); 183 184// If there are events, return the keys directly 185if (maxlen && pending_events (events )) { 186return push_event_key (buf ,maxlen ); 187 } 188 189return 0 ; 190 191#undef TRY_READ 192} 193 194// Check if a character is available for reading 195bool os_char_avail (void ) 196{ 197return inbuf_poll (0 ,NULL ); 198} 199 200/// Poll for fast events. `got_int` will be set to `true` if CTRL-C was typed. 201/// 202/// This invokes a full libuv loop iteration which can be quite costly. 203/// Prefer `line_breakcheck()` if called in a busy inner loop. 204/// 205/// Caller must at least check `got_int` before calling this function again. 206/// checking for other low-level input state like `input_available()` might 207/// also be relevant (i e to throttle idle processing when user input is 208/// available) 209void os_breakcheck (void ) 210{ 211if (got_int ) { 212return ; 213 } 214 215loop_poll_events (& main_loop ,0 ); 216} 217 218#define BREAKCHECK_SKIP 1000 219static int breakcheck_count = 0 ; 220 221/// Check for CTRL-C pressed, but only once in a while. 222/// 223/// Should be used instead of os_breakcheck() for functions that check for 224/// each line in the file. Calling os_breakcheck() each time takes too much 225/// time, because it will use system calls to check for input. 226void line_breakcheck (void ) 227{ 228if (++ breakcheck_count >=BREAKCHECK_SKIP ) { 229breakcheck_count = 0 ; 230os_breakcheck (); 231 } 232} 233 234/// Like line_breakcheck() but check 10 times less often. 235void fast_breakcheck (void ) 236{ 237if (++ breakcheck_count >=BREAKCHECK_SKIP * 10 ) { 238breakcheck_count = 0 ; 239os_breakcheck (); 240 } 241} 242 243/// Like line_breakcheck() but check 100 times less often. 244void veryfast_breakcheck (void ) 245{ 246if (++ breakcheck_count >=BREAKCHECK_SKIP * 100 ) { 247breakcheck_count = 0 ; 248os_breakcheck (); 249 } 250} 251 252/// Test whether a file descriptor refers to a terminal. 253/// 254/// @param fd File descriptor. 255/// @return `true` if file descriptor refers to a terminal. 256bool os_isatty (int fd ) 257{ 258return uv_guess_handle (fd )== UV_TTY ; 259} 260 261size_t input_available (void ) 262{ 263return (size_t )(input_write_pos - input_read_pos ); 264} 265 266static size_t input_space (void ) 267{ 268return (size_t )(input_buffer + INPUT_BUFFER_SIZE - input_write_pos ); 269} 270 271void input_enqueue_raw (const char * data ,size_t size ) 272{ 273if (input_read_pos > input_buffer ) { 274size_t available = input_available (); 275memmove (input_buffer ,input_read_pos ,available ); 276input_read_pos = input_buffer ; 277input_write_pos = input_buffer + available ; 278 } 279 280size_t to_write = MIN (size ,input_space ()); 281memcpy (input_write_pos ,data ,to_write ); 282input_write_pos += to_write ; 283} 284 285size_t input_enqueue (uint64_t chan_id ,String keys ) 286{ 287current_ui = chan_id ; 288 289// If the buffer has been fully drained, rewind the read/write cursors to the 290// start to reclaim tail space. Otherwise a drained-but-not-rewound buffer left 291// pinned within <19 bytes of the top (input_get() advances input_read_pos but 292// never rewinds it) would fail the `input_space() >= 19` gate below forever, 293// silently dropping all further input and freezing the editor. 294if (input_read_pos == input_write_pos ) { 295input_read_pos = input_buffer ; 296input_write_pos = input_buffer ; 297 } 298 299if (keys .size > 0 ) { 300set_vim_var_nr (VV_USERACTIVE , (varnumber_T )os_realtime ()); 301 } 302 303const char * ptr = keys .data ; 304const char * end = ptr + keys .size ; 305 306while (input_space () >=19 && ptr < end ) { 307// A "<x>" form occupies at least 1 characters, and produces up 308// to 19 characters (1 + 5 * 3 for the char and 3 for a modifier). 309// In the case of K_SPECIAL (0x80), 3 bytes are escaped and needed, 310// but since the keys are UTF-8, so the first byte cannot be 311// K_SPECIAL (0x80). 312uint8_t buf [19 ]= {0 }; 313// Do not simplify the keys here. Simplification will be done later. 314unsigned new_size 315= trans_special (& ptr , (size_t )(end - ptr ), (char * )buf ,FSK_KEYCODE , true,NULL ); 316 317if (new_size > 0 ) { 318if ((new_size = handle_mouse_event (& ptr ,buf ,new_size ))> 0 ) { 319input_enqueue_raw ((char * )buf ,new_size ); 320 } 321continue ; 322 } 323 324if (* ptr == '<' ) { 325const char * old_ptr = ptr ; 326// Invalid or incomplete key sequence, skip until the next '>' or *end. 327do { 328ptr ++ ; 329 }while (ptr < end && * ptr != '>' ); 330if (* ptr != '>' ) { 331// Incomplete key sequence, return without consuming. 332ptr = old_ptr ; 333break ; 334 } 335ptr ++ ; 336continue ; 337 } 338 339// copy the character, escaping K_SPECIAL 340if ((uint8_t )(* ptr )== K_SPECIAL ) { 341input_enqueue_raw ((char * )& (uint8_t ){K_SPECIAL },1 ); 342input_enqueue_raw ((char * )& (uint8_t ){KS_SPECIAL },1 ); 343input_enqueue_raw ((char * )& (uint8_t ){KE_FILLER },1 ); 344 }else { 345input_enqueue_raw (ptr ,1 ); 346 } 347ptr ++ ; 348 } 349 350size_t rv = (size_t )(ptr - keys .data ); 351process_ctrl_c (); 352return rv ; 353} 354 355static uint8_t check_multiclick (int code ,int grid ,int row ,int col ,bool * skip_event ) 356{ 357static int orig_num_clicks = 0 ; 358static int orig_mouse_code = 0 ; 359static int orig_mouse_grid = 0 ; 360static int orig_mouse_col = 0 ; 361static int orig_mouse_row = 0 ; 362static uint64_t orig_mouse_time = 0 ;// time of previous mouse click 363 364if (code >=KE_MOUSEDOWN && code <=KE_MOUSERIGHT ) { 365return 0 ; 366 } 367 368bool no_move = orig_mouse_grid == grid && orig_mouse_col == col && orig_mouse_row == row ; 369bool is_click ,is_drag ; 370 (void )get_mouse_button (code ,& is_click ,& is_drag ); 371 372if (is_drag && no_move ) { 373* skip_event = true; 374return 0 ; 375 } 376 377if (is_click ) { 378// For click events the number of clicks is updated. 379uint64_t mouse_time = os_hrtime ();// time of current mouse click (ns) 380// Compute the time elapsed since the previous mouse click. 381uint64_t timediff = mouse_time - orig_mouse_time ; 382// Convert 'mousetime' from ms to ns. 383uint64_t mouset = (uint64_t )p_mouset * 1000000 ; 384if (code == orig_mouse_code 385&& no_move 386&& timediff < mouset 387&& orig_num_clicks != 4 ) { 388orig_num_clicks ++ ; 389 }else { 390orig_num_clicks = 1 ; 391 } 392orig_mouse_code = code ; 393orig_mouse_time = mouse_time ; 394 }else if (!no_move ) { 395// For drag and release events the number of clicks is kept. 396// However, if the mouse has moved, the next click should reset the click count. 397orig_mouse_code = code ; 398 } 399 400orig_mouse_grid = grid ; 401orig_mouse_col = col ; 402orig_mouse_row = row ; 403 404uint8_t modifiers = 0 ; 405if (code != KE_MOUSEMOVE ) { 406if (orig_num_clicks == 2 ) { 407modifiers |=MOD_MASK_2CLICK ; 408 }else if (orig_num_clicks == 3 ) { 409modifiers |=MOD_MASK_3CLICK ; 410 }else if (orig_num_clicks == 4 ) { 411modifiers |=MOD_MASK_4CLICK ; 412 } 413 } 414return modifiers ; 415} 416 417/// Mouse event handling code (extract row/col if available and detect multiple clicks) 418static unsigned handle_mouse_event (const char ** ptr ,uint8_t * buf ,unsigned bufsize ) 419{ 420int mouse_code = 0 ; 421int type = 0 ; 422 423if (bufsize == 3 ) { 424mouse_code = buf [2 ]; 425type = buf [1 ]; 426 }else if (bufsize == 6 ) { 427// prefixed with K_SPECIAL KS_MODIFIER mod 428mouse_code = buf [5 ]; 429type = buf [4 ]; 430 } 431 432if (type != KS_EXTRA 433|| !((mouse_code >=KE_LEFTMOUSE && mouse_code <=KE_RIGHTRELEASE ) 434|| (mouse_code >=KE_X1MOUSE && mouse_code <=KE_X2RELEASE ) 435|| (mouse_code >=KE_MOUSEDOWN && mouse_code <=KE_MOUSERIGHT ) 436|| mouse_code == KE_MOUSEMOVE )) { 437return bufsize ; 438 } 439 440// A <[COL],[ROW]> sequence can follow and will set the mouse_row/mouse_col 441// global variables. This is ugly but its how the rest of the code expects to 442// find mouse coordinates, and it would be too expensive to refactor this 443// now. 444int col ,row ,advance ; 445if (sscanf (* ptr ,"<%d,%d>%n" ,& col ,& row ,& advance )!= EOF && advance ) { 446if (col >=0 && row >=0 ) { 447// Make sure the mouse position is valid. Some terminals may 448// return weird values. 449if (col >=Columns ) { 450col = Columns - 1 ; 451 } 452if (row >=Rows ) { 453row = Rows - 1 ; 454 } 455mouse_grid = 0 ; 456mouse_row = row ; 457mouse_col = col ; 458 } 459* ptr += advance ; 460 } 461 462bool skip_event = false; 463uint8_t modifiers = check_multiclick (mouse_code ,mouse_grid , 464mouse_row ,mouse_col ,& skip_event ); 465if (skip_event ) { 466return 0 ; 467 } 468 469if (modifiers ) { 470if (buf [1 ]!= KS_MODIFIER ) { 471// no modifiers in the buffer yet, shift the bytes 3 positions 472memcpy (buf + 3 ,buf ,3 ); 473// add the modifier sequence 474buf [0 ]= K_SPECIAL ; 475buf [1 ]= KS_MODIFIER ; 476buf [2 ]= modifiers ; 477bufsize += 3 ; 478 }else { 479buf [2 ] |=modifiers ; 480 } 481 } 482 483return bufsize ; 484} 485 486void input_enqueue_mouse (int code ,uint8_t modifier ,int grid ,int row ,int col ) 487{ 488bool skip_event = false; 489modifier |=check_multiclick (code ,grid ,row ,col ,& skip_event ); 490if (skip_event ) { 491return ; 492 } 493uint8_t buf [7 ]; 494uint8_t * p = buf ; 495if (modifier ) { 496p [0 ]= K_SPECIAL ; 497p [1 ]= KS_MODIFIER ; 498p [2 ]= modifier ; 499p += 3 ; 500 } 501p [0 ]= K_SPECIAL ; 502p [1 ]= KS_EXTRA ; 503p [2 ]= (uint8_t )code ; 504 505mouse_grid = grid ; 506mouse_row = row ; 507mouse_col = col ; 508 509size_t written = 3 + (size_t )(p - buf ); 510input_enqueue_raw ((char * )buf ,written ); 511} 512 513/// @return true if the main loop is blocked and waiting for input. 514bool input_blocking (void ) 515{ 516return blocking ; 517} 518 519/// Checks for (but does not read) available input, and consumes `main_loop.events` while waiting. 520/// 521/// @param ms Timeout in milliseconds. -1 for indefinite wait, 0 for no wait. 522/// @param events (optional) Queue to check for pending events. 523/// @return true if input or events are available. 524static bool inbuf_poll (int ms ,MultiQueue * events ) 525{ 526if (os_input_ready (events )) { 527return true; 528 } 529 530if (do_profiling == PROF_YES && ms ) { 531prof_input_start (); 532 } 533 534if ((ms == -1 || ms > 0 )&& events != main_loop .events ) { 535// The pending input provoked a blocking wait. Do special events now. #6247 536blocking = true; 537multiqueue_process_events (ch_before_blocking_events ); 538 } 539DLOG ("blocking... events=%s" , !!events ?"true" :"false" ); 540LOOP_PROCESS_EVENTS_UNTIL (& main_loop ,NULL ,ms ,os_input_ready (events )); 541blocking = false; 542 543if (do_profiling == PROF_YES && ms ) { 544prof_input_end (); 545 } 546 547return os_input_ready (events ); 548} 549 550static void process_ctrl_c (void ) 551{ 552if (!ctrl_c_interrupts ) { 553return ; 554 } 555 556size_t available = input_available (); 557ssize_t i ; 558for (i = (ssize_t )available - 1 ;i >=0 ;i -- ) {// Reverse-search input for Ctrl_C. 559uint8_t c = (uint8_t )input_read_pos [i ]; 560if (c == Ctrl_C 561|| (c == 'C' && i >=3 562&& (uint8_t )input_read_pos [i - 3 ]== K_SPECIAL 563&& (uint8_t )input_read_pos [i - 2 ]== KS_MODIFIER 564&& (uint8_t )input_read_pos [i - 1 ]== MOD_MASK_CTRL )) { 565input_read_pos [i ]= Ctrl_C ; 566got_int = true; 567break ; 568 } 569 } 570 571if (got_int && i > 0 ) { 572// Remove all unprocessed input (typeahead) before the CTRL-C. 573input_read_pos += i ; 574 } 575} 576 577/// Pushes bytes from the "event" key sequence (KE_EVENT) partially between calls to input_get when 578/// `maxlen < 3`. 579static int push_event_key (uint8_t * buf ,int maxlen ) 580{ 581static const uint8_t key [3 ]= {K_SPECIAL ,KS_EXTRA ,KE_EVENT }; 582static int key_idx = 0 ; 583int buf_idx = 0 ; 584 585do { 586buf [buf_idx ++ ]= key [key_idx ++ ]; 587key_idx %=3 ; 588 }while (key_idx > 0 && buf_idx < maxlen ); 589 590return buf_idx ; 591} 592 593/// Check if there's pending input already in typebuf or `events` 594bool os_input_ready (MultiQueue * events ) 595{ 596return (typebuf_was_filled // API call filled typeahead 597|| input_available ()// Input buffer filled 598|| pending_events (events ));// Events must be processed 599} 600 601static bool pending_events (MultiQueue * events ) 602{ 603return events && !multiqueue_empty (events ); 604}