robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyesrefactor(exmode): Ex-mode as cmdwin + Lua #40991359459dec6

master
17.7 KiB604 linesraw
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{
53  event_T event = State & MODE_INSERT ? EVENT_CURSORHOLDI : EVENT_CURSORHOLD;
54  apply_autocmds(event, NULL, NULL, false, curbuf);
55  did_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.
64  assert(!events_enabled || multiqueue_empty(main_loop.events));
65  multiqueue_put(main_loop.events, cursorhold_event, NULL);
66}
67
68static void reset_cursorhold_wait(int tb_change_cnt)
69{
70  cursorhold_time = 0;
71  cursorhold_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{
91  assert((maxlen > 0 && buf != NULL) || maxlen == 0);
92  // This check is needed so that feeding typeahead from RPC can prevent CursorHold.
93  if (tb_change_cnt != cursorhold_tb_change_cnt) {
94    reset_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. */ \
105      assert(to_read <= INT_MAX); \
106      return (int)to_read; \
107    } \
108  } while (0)
109
110  TRY_READ();
111
112  // No risk of a UI flood, so disable CTRL-C "interrupt" behavior if it's mapped.
113  if ((mapped_ctrl_c | curbuf->b_mapped_ctrl_c) & get_real_state()) {
114    ctrl_c_interrupts = false;
115  }
116
117  if (ms >= 0) {
118    if (!inbuf_poll(ms, events)) {
119      return 0;
120    }
121  } else {
122    uint64_t wait_start = os_hrtime();
123    cursorhold_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).
130    bool 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.
136    int64_t wait_time = p_ut - cursorhold_time;
137    if (delay_pending) {
138      int64_t delay_left = p_acl - ins_compl_autocomplete_elapsed();
139      wait_time = MIN(MAX(delay_left, 0), wait_time);
140    }
141    if (!inbuf_poll((int)wait_time, events)) {
142      if (silent_mode) {
143        // Ran out of input: exit silent/batch-mode (-es/-Es).
144        getout(0);
145      }
146      // The 'autocompletedelay' expired: trigger the popup.  When
147      // 'updatetime' is shorter, fall through to CursorHold instead.
148      if (delay_pending && ins_compl_autocomplete_elapsed() >= p_acl
149          && (buf == NULL || maxlen >= 3) && !typebuf_changed(tb_change_cnt)) {
150        if (buf == NULL) {
151          uint8_t ibuf[3];
152          ibuf[0] = K_SPECIAL;
153          ibuf[1] = KS_EXTRA;
154          ibuf[2] = KE_COMPLETE_DELAY;
155          input_enqueue_raw((char *)ibuf, 3);
156          return 0;
157        }
158        buf[0] = K_SPECIAL;
159        buf[1] = KS_EXTRA;
160        buf[2] = KE_COMPLETE_DELAY;
161        return 3;
162      }
163      reset_cursorhold_wait(tb_change_cnt);
164      if (trigger_cursorhold() && !typebuf_changed(tb_change_cnt)) {
165        create_cursorhold_event(events == main_loop.events);
166      } else {
167        before_blocking();
168        inbuf_poll(-1, events);
169      }
170    } else {
171      cursorhold_time += (int)((os_hrtime() - wait_start) / 1000000);
172    }
173  }
174
175  ctrl_c_interrupts = true;
176
177  // If input was put directly in typeahead buffer bail out here.
178  if (typebuf_changed(tb_change_cnt)) {
179    return 0;
180  }
181
182  TRY_READ();
183
184  // If there are events, return the keys directly
185  if (maxlen && pending_events(events)) {
186    return push_event_key(buf, maxlen);
187  }
188
189  return 0;
190
191#undef TRY_READ
192}
193
194// Check if a character is available for reading
195bool os_char_avail(void)
196{
197  return 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{
211  if (got_int) {
212    return;
213  }
214
215  loop_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{
228  if (++breakcheck_count >= BREAKCHECK_SKIP) {
229    breakcheck_count = 0;
230    os_breakcheck();
231  }
232}
233
234/// Like line_breakcheck() but check 10 times less often.
235void fast_breakcheck(void)
236{
237  if (++breakcheck_count >= BREAKCHECK_SKIP * 10) {
238    breakcheck_count = 0;
239    os_breakcheck();
240  }
241}
242
243/// Like line_breakcheck() but check 100 times less often.
244void veryfast_breakcheck(void)
245{
246  if (++breakcheck_count >= BREAKCHECK_SKIP * 100) {
247    breakcheck_count = 0;
248    os_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{
258  return uv_guess_handle(fd) == UV_TTY;
259}
260
261size_t input_available(void)
262{
263  return (size_t)(input_write_pos - input_read_pos);
264}
265
266static size_t input_space(void)
267{
268  return (size_t)(input_buffer + INPUT_BUFFER_SIZE - input_write_pos);
269}
270
271void input_enqueue_raw(const char *data, size_t size)
272{
273  if (input_read_pos > input_buffer) {
274    size_t available = input_available();
275    memmove(input_buffer, input_read_pos, available);
276    input_read_pos = input_buffer;
277    input_write_pos = input_buffer + available;
278  }
279
280  size_t to_write = MIN(size, input_space());
281  memcpy(input_write_pos, data, to_write);
282  input_write_pos += to_write;
283}
284
285size_t input_enqueue(uint64_t chan_id, String keys)
286{
287  current_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.
294  if (input_read_pos == input_write_pos) {
295    input_read_pos = input_buffer;
296    input_write_pos = input_buffer;
297  }
298
299  if (keys.size > 0) {
300    set_vim_var_nr(VV_USERACTIVE, (varnumber_T)os_realtime());
301  }
302
303  const char *ptr = keys.data;
304  const char *end = ptr + keys.size;
305
306  while (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).
312    uint8_t buf[19] = { 0 };
313    // Do not simplify the keys here. Simplification will be done later.
314    unsigned new_size
315      = trans_special(&ptr, (size_t)(end - ptr), (char *)buf, FSK_KEYCODE, true, NULL);
316
317    if (new_size > 0) {
318      if ((new_size = handle_mouse_event(&ptr, buf, new_size)) > 0) {
319        input_enqueue_raw((char *)buf, new_size);
320      }
321      continue;
322    }
323
324    if (*ptr == '<') {
325      const char *old_ptr = ptr;
326      // Invalid or incomplete key sequence, skip until the next '>' or *end.
327      do {
328        ptr++;
329      } while (ptr < end && *ptr != '>');
330      if (*ptr != '>') {
331        // Incomplete key sequence, return without consuming.
332        ptr = old_ptr;
333        break;
334      }
335      ptr++;
336      continue;
337    }
338
339    // copy the character, escaping K_SPECIAL
340    if ((uint8_t)(*ptr) == K_SPECIAL) {
341      input_enqueue_raw((char *)&(uint8_t){ K_SPECIAL }, 1);
342      input_enqueue_raw((char *)&(uint8_t){ KS_SPECIAL }, 1);
343      input_enqueue_raw((char *)&(uint8_t){ KE_FILLER }, 1);
344    } else {
345      input_enqueue_raw(ptr, 1);
346    }
347    ptr++;
348  }
349
350  size_t rv = (size_t)(ptr - keys.data);
351  process_ctrl_c();
352  return rv;
353}
354
355static uint8_t check_multiclick(int code, int grid, int row, int col, bool *skip_event)
356{
357  static int orig_num_clicks = 0;
358  static int orig_mouse_code = 0;
359  static int orig_mouse_grid = 0;
360  static int orig_mouse_col = 0;
361  static int orig_mouse_row = 0;
362  static uint64_t orig_mouse_time = 0;  // time of previous mouse click
363
364  if (code >= KE_MOUSEDOWN && code <= KE_MOUSERIGHT) {
365    return 0;
366  }
367
368  bool no_move = orig_mouse_grid == grid && orig_mouse_col == col && orig_mouse_row == row;
369  bool is_click, is_drag;
370  (void)get_mouse_button(code, &is_click, &is_drag);
371
372  if (is_drag && no_move) {
373    *skip_event = true;
374    return 0;
375  }
376
377  if (is_click) {
378    // For click events the number of clicks is updated.
379    uint64_t mouse_time = os_hrtime();    // time of current mouse click (ns)
380    // Compute the time elapsed since the previous mouse click.
381    uint64_t timediff = mouse_time - orig_mouse_time;
382    // Convert 'mousetime' from ms to ns.
383    uint64_t mouset = (uint64_t)p_mouset * 1000000;
384    if (code == orig_mouse_code
385        && no_move
386        && timediff < mouset
387        && orig_num_clicks != 4) {
388      orig_num_clicks++;
389    } else {
390      orig_num_clicks = 1;
391    }
392    orig_mouse_code = code;
393    orig_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.
397    orig_mouse_code = code;
398  }
399
400  orig_mouse_grid = grid;
401  orig_mouse_col = col;
402  orig_mouse_row = row;
403
404  uint8_t modifiers = 0;
405  if (code != KE_MOUSEMOVE) {
406    if (orig_num_clicks == 2) {
407      modifiers |= MOD_MASK_2CLICK;
408    } else if (orig_num_clicks == 3) {
409      modifiers |= MOD_MASK_3CLICK;
410    } else if (orig_num_clicks == 4) {
411      modifiers |= MOD_MASK_4CLICK;
412    }
413  }
414  return 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{
420  int mouse_code = 0;
421  int type = 0;
422
423  if (bufsize == 3) {
424    mouse_code = buf[2];
425    type = buf[1];
426  } else if (bufsize == 6) {
427    // prefixed with K_SPECIAL KS_MODIFIER mod
428    mouse_code = buf[5];
429    type = buf[4];
430  }
431
432  if (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)) {
437    return 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.
444  int col, row, advance;
445  if (sscanf(*ptr, "<%d,%d>%n", &col, &row, &advance) != EOF && advance) {
446    if (col >= 0 && row >= 0) {
447      // Make sure the mouse position is valid.  Some terminals may
448      // return weird values.
449      if (col >= Columns) {
450        col = Columns - 1;
451      }
452      if (row >= Rows) {
453        row = Rows - 1;
454      }
455      mouse_grid = 0;
456      mouse_row = row;
457      mouse_col = col;
458    }
459    *ptr += advance;
460  }
461
462  bool skip_event = false;
463  uint8_t modifiers = check_multiclick(mouse_code, mouse_grid,
464                                       mouse_row, mouse_col, &skip_event);
465  if (skip_event) {
466    return 0;
467  }
468
469  if (modifiers) {
470    if (buf[1] != KS_MODIFIER) {
471      // no modifiers in the buffer yet, shift the bytes 3 positions
472      memcpy(buf + 3, buf, 3);
473      // add the modifier sequence
474      buf[0] = K_SPECIAL;
475      buf[1] = KS_MODIFIER;
476      buf[2] = modifiers;
477      bufsize += 3;
478    } else {
479      buf[2] |= modifiers;
480    }
481  }
482
483  return bufsize;
484}
485
486void input_enqueue_mouse(int code, uint8_t modifier, int grid, int row, int col)
487{
488  bool skip_event = false;
489  modifier |= check_multiclick(code, grid, row, col, &skip_event);
490  if (skip_event) {
491    return;
492  }
493  uint8_t buf[7];
494  uint8_t *p = buf;
495  if (modifier) {
496    p[0] = K_SPECIAL;
497    p[1] = KS_MODIFIER;
498    p[2] = modifier;
499    p += 3;
500  }
501  p[0] = K_SPECIAL;
502  p[1] = KS_EXTRA;
503  p[2] = (uint8_t)code;
504
505  mouse_grid = grid;
506  mouse_row = row;
507  mouse_col = col;
508
509  size_t written = 3 + (size_t)(p - buf);
510  input_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{
516  return 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{
526  if (os_input_ready(events)) {
527    return true;
528  }
529
530  if (do_profiling == PROF_YES && ms) {
531    prof_input_start();
532  }
533
534  if ((ms == -1 || ms > 0) && events != main_loop.events) {
535    // The pending input provoked a blocking wait. Do special events now. #6247
536    blocking = true;
537    multiqueue_process_events(ch_before_blocking_events);
538  }
539  DLOG("blocking... events=%s", !!events ? "true" : "false");
540  LOOP_PROCESS_EVENTS_UNTIL(&main_loop, NULL, ms, os_input_ready(events));
541  blocking = false;
542
543  if (do_profiling == PROF_YES && ms) {
544    prof_input_end();
545  }
546
547  return os_input_ready(events);
548}
549
550static void process_ctrl_c(void)
551{
552  if (!ctrl_c_interrupts) {
553    return;
554  }
555
556  size_t available = input_available();
557  ssize_t i;
558  for (i = (ssize_t)available - 1; i >= 0; i--) {  // Reverse-search input for Ctrl_C.
559    uint8_t c = (uint8_t)input_read_pos[i];
560    if (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)) {
565      input_read_pos[i] = Ctrl_C;
566      got_int = true;
567      break;
568    }
569  }
570
571  if (got_int && i > 0) {
572    // Remove all unprocessed input (typeahead) before the CTRL-C.
573    input_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{
581  static const uint8_t key[3] = { K_SPECIAL, KS_EXTRA, KE_EVENT };
582  static int key_idx = 0;
583  int buf_idx = 0;
584
585  do {
586    buf[buf_idx++] = key[key_idx++];
587    key_idx %= 3;
588  } while (key_idx > 0 && buf_idx < maxlen);
589
590  return buf_idx;
591}
592
593/// Check if there's pending input already in typebuf or `events`
594bool os_input_ready(MultiQueue *events)
595{
596  return (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{
603  return events && !multiqueue_empty(events);
604}