robin/laufey

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

Justin M. Keyesrefactor(detach): eliminate `nvim__ui_detach` #40793e0e7f65b74

master
32.0 KiB1106 linesraw
1#include <assert.h>
2#include <inttypes.h>
3#include <stdbool.h>
4#include <stddef.h>
5#include <stdint.h>
6#include <stdlib.h>
7#include <string.h>
8
9#include "klib/kvec.h"
10#include "nvim/api/private/converter.h"
11#include "nvim/api/private/defs.h"
12#include "nvim/api/private/helpers.h"
13#include "nvim/api/private/validate.h"
14#include "nvim/api/ui.h"
15#include "nvim/assert_defs.h"
16#include "nvim/autocmd.h"
17#include "nvim/autocmd_defs.h"
18#include "nvim/channel.h"
19#include "nvim/channel_defs.h"
20#include "nvim/errors.h"
21#include "nvim/eval/typval.h"
22#include "nvim/eval/vars.h"
23#include "nvim/event/defs.h"
24#include "nvim/event/loop.h"
25#include "nvim/event/multiqueue.h"
26#include "nvim/event/wstream.h"
27#include "nvim/globals.h"
28#include "nvim/grid.h"
29#include "nvim/highlight.h"
30#include "nvim/macros_defs.h"
31#include "nvim/main.h"
32#include "nvim/map_defs.h"
33#include "nvim/mbyte.h"
34#include "nvim/memory.h"
35#include "nvim/memory_defs.h"
36#include "nvim/msgpack_rpc/channel.h"
37#include "nvim/msgpack_rpc/channel_defs.h"
38#include "nvim/msgpack_rpc/packer.h"
39#include "nvim/msgpack_rpc/packer_defs.h"
40#include "nvim/option.h"
41#include "nvim/types_defs.h"
42#include "nvim/ui.h"
43
44#ifdef MSWIN
45# include "nvim/os/os_win_console.h"
46#endif
47
48#define BUF_POS(ui) ((size_t)((ui)->packer.ptr - (ui)->packer.startptr))
49
50#include "api/ui.c.generated.h"
51#include "ui_events_remote.generated.h"  // IWYU pragma: export
52
53// TODO(bfredl): just make UI:s owned by their channels instead
54static PMap(uint64_t) connected_uis = MAP_INIT;
55
56/// Gets the UI attached to the given channel, or sets an error message on `err`.
57static RemoteUI *get_ui_or_err(uint64_t chan_id, Error *err)
58{
59  RemoteUI *ui = pmap_get(uint64_t)(&connected_uis, chan_id);
60  if (ui == NULL && err != NULL) {
61    api_set_error(err, kErrorTypeException, "UI not attached to channel: %" PRId64, chan_id);
62  }
63  return ui;
64}
65
66static char *mpack_array_dyn16(char **buf)
67{
68  mpack_w(buf, 0xdc);
69  char *pos = *buf;
70  mpack_w2(buf, 0xFFEF);
71  return pos;
72}
73
74static void mpack_str_small(char **buf, const char *str, size_t len)
75{
76  assert(len < 0x20);
77  mpack_w(buf, 0xa0 | len);
78  memcpy(*buf, str, len);
79  *buf += len;
80}
81
82static void remote_ui_destroy(RemoteUI *ui)
83  FUNC_ATTR_NONNULL_ALL
84{
85  xfree(ui->packer.startptr);
86  XFREE_CLEAR(ui->term_name);
87  xfree(ui);
88}
89
90/// Removes the client on the given channel from the list of UIs.
91///
92/// @param err  if non-NULL and there is no UI on the channel, set an error
93/// @param send_error_exit  send an "error_exit" event with 0 status first
94void remote_ui_disconnect(uint64_t channel_id, Error *err, bool send_error_exit)
95{
96  RemoteUI *ui = get_ui_or_err(channel_id, err);
97  if (!ui) {
98    return;
99  }
100  if (send_error_exit) {
101    MAXSIZE_TEMP_ARRAY(args, 1);
102    ADD_C(args, INTEGER_OBJ(0));
103    push_call(ui, "error_exit", args);
104    ui_flush_buf(ui, false);
105  }
106  pmap_del(uint64_t)(&connected_uis, channel_id, NULL);
107  ui_detach_impl(ui, channel_id);
108  Channel *chan = find_channel(channel_id);
109  if (chan && chan->rpc.ui == ui) {
110    chan->rpc.ui = NULL;
111  }
112
113  remote_ui_destroy(ui);
114}
115
116/// Detaches the UI on channel `chan` (server keeps running). Sets `channel.detach`, sends an
117/// "error_exit" UI event, and closes the channel.
118///
119/// @param chan  UI channel to disconnect.
120/// @param[out] err Error details, if any.
121void ui_detach_channel(uint64_t chan, Error *err)
122{
123  Channel *c = find_channel(chan);
124  VALIDATE(c != NULL, "%s", e_invchan, {
125    return;
126  });
127#ifdef MSWIN
128  bool detach_stdio = c->streamtype == kChannelStreamStdio;
129#endif
130  // Prevent server self-exit on channel-close.
131  c->detach = true;
132  // Server-side UI detach. Doesn't close the channel.
133  remote_ui_disconnect(chan, err, true);
134  if (ERROR_SET(err)) {
135    return;
136  }
137  // Server-side channel close.
138  channel_close(chan, kChannelPartAll, NULL);
139#ifdef MSWIN
140  if (detach_stdio) {
141    // After UI/channel detach, move this server off the parent's console so it
142    // survives terminal closure and still has working CONIN$/CONOUT$.
143    os_swap_to_hidden_console();
144  }
145#endif
146}
147
148/// Detaches every UI except `keep_chan` (server keeps running).
149///
150/// @param keep_chan  UI channel to preserve.
151/// @return Number of UIs detached.
152size_t ui_detach_others(uint64_t keep_chan)
153{
154  // Snapshot the channel ids first: ui_detach_channel() mutates connected_uis.
155  kvec_t(uint64_t) chans = KV_INITIAL_VALUE;
156  uint64_t chan;
157  map_foreach_key(&connected_uis, chan, {
158    if (chan != keep_chan) {
159      kv_push(chans, chan);
160    }
161  });
162
163  size_t detached = 0;
164  for (size_t i = 0; i < kv_size(chans); i++) {
165    Error err = ERROR_INIT;
166    ui_detach_channel(kv_A(chans, i), &err);
167    if (ERROR_SET(&err)) {
168      api_clear_error(&err);
169    } else {
170      detached++;
171    }
172  }
173
174  kv_destroy(chans);
175  return detached;
176}
177
178#ifdef EXITFREE
179void remote_ui_free_all_mem(void)
180{
181  RemoteUI *ui;
182  map_foreach_value(&connected_uis, ui, {
183    remote_ui_destroy(ui);
184  });
185  map_destroy(uint64_t, &connected_uis);
186}
187#endif
188
189/// Wait until UI has connected.
190void remote_ui_wait_for_attach(void)
191{
192  LOOP_PROCESS_EVENTS_UNTIL(&main_loop, main_loop.events, -1, ui_active());
193}
194
195/// Activates UI events on the channel.
196///
197/// Entry point of all UI clients.  Allows |--embed| to continue startup.
198/// Implies that the client is ready to show the UI.  Adds the client to the
199/// list of UIs. |nvim_list_uis()|
200///
201/// @note If multiple UI clients are attached, the global screen dimensions
202///       degrade to the smallest client. E.g. if client A requests 80x40 but
203///       client B requests 200x100, the global screen has size 80x40.
204///
205/// @param channel_id
206/// @param width  Requested screen columns
207/// @param height  Requested screen rows
208/// @param options  |ui-option| map
209/// @param[out] err Error details, if any
210void nvim_ui_attach(uint64_t channel_id, Integer width, Integer height, Dict options, Error *err)
211  FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
212{
213  if (map_has(uint64_t, &connected_uis, channel_id)) {
214    api_set_error(err, kErrorTypeException,
215                  "UI already attached to channel: %" PRId64, channel_id);
216    return;
217  }
218  if (!ui_can_attach_more()) {
219    api_set_error(err, kErrorTypeException, "Maximum UI count reached");
220    return;
221  }
222
223  if (width <= 0 || height <= 0) {
224    api_set_error(err, kErrorTypeValidation, "Expected width > 0 and height > 0");
225    return;
226  }
227  RemoteUI *ui = xcalloc(1, sizeof(RemoteUI));
228  ui->channel_id = channel_id;
229  ui->width = (int)width;
230  ui->height = (int)height;
231  ui->pum_row = -1.0;
232  ui->pum_col = -1.0;
233  ui->rgb = true;
234  CLEAR_FIELD(ui->ui_ext);
235
236  for (size_t i = 0; i < options.size; i++) {
237    ui_set_option(ui, true, options.items[i].key, options.items[i].value, err);
238    if (ERROR_SET(err)) {
239      xfree(ui);
240      return;
241    }
242  }
243
244  if (ui->ui_ext[kUIHlState] || ui->ui_ext[kUIMultigrid]) {
245    ui->ui_ext[kUILinegrid] = true;
246  }
247
248  if (ui->ui_ext[kUIMessages]) {
249    // This uses attribute indices, so ext_linegrid is needed.
250    ui->ui_ext[kUILinegrid] = true;
251    // Cmdline uses the messages area, so it should be externalized too.
252    ui->ui_ext[kUICmdline] = true;
253  }
254
255  ui->cur_event = NULL;
256  ui->hl_id = 0;
257  ui->client_col = -1;
258  ui->nevents_pos = NULL;
259  ui->nevents = 0;
260  ui->flushed_events = false;
261  ui->incomplete_event = false;
262  ui->ncalls_pos = NULL;
263  ui->ncalls = 0;
264  ui->ncells_pending = 0;
265  ui->packer = (PackerBuffer) {
266    .startptr = NULL,
267    .ptr = NULL,
268    .endptr = NULL,
269    .packer_flush = ui_flush_callback,
270    .anydata = ui,
271  };
272  ui->wildmenu_active = false;
273
274  pmap_put(uint64_t)(&connected_uis, channel_id, ui);
275  current_ui = channel_id;
276  ui_attach_impl(ui, channel_id);
277
278  Channel *chan = find_channel(channel_id);
279  if (chan) {
280    chan->rpc.ui = ui;
281  }
282
283  may_trigger_vim_suspend_resume(false);
284}
285
286/// @deprecated
287void ui_attach(uint64_t channel_id, Integer width, Integer height, Boolean enable_rgb, Error *err)
288  FUNC_API_DEPRECATED_SINCE(1)
289{
290  MAXSIZE_TEMP_DICT(opts, 1);
291  PUT_C(opts, "rgb", BOOLEAN_OBJ(enable_rgb));
292  nvim_ui_attach(channel_id, width, height, opts, err);
293}
294
295/// Tells the nvim server if focus was gained or lost by the GUI
296void nvim_ui_set_focus(uint64_t channel_id, Boolean gained, Error *error)
297  FUNC_API_SINCE(11) FUNC_API_REMOTE_ONLY
298{
299  if (!get_ui_or_err(channel_id, error)) {
300    return;
301  }
302
303  if (gained) {
304    current_ui = channel_id;
305    may_trigger_vim_suspend_resume(false);
306  }
307
308  do_autocmd_focusgained((bool)gained);
309}
310
311/// Deactivates UI events on the channel.
312///
313/// Removes the client from the list of UIs. |nvim_list_uis()|
314///
315/// @param channel_id
316/// @param[out] err Error details, if any
317void nvim_ui_detach(uint64_t channel_id, Error *err)
318  FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
319{
320  remote_ui_disconnect(channel_id, err, false);
321}
322
323// Send a connect UI event to the UI on the given channel
324void remote_ui_connect(uint64_t channel_id, char *server_addr, Error *err)
325{
326  RemoteUI *ui = get_ui_or_err(channel_id, err);
327  if (!ui) {
328    return;
329  }
330
331  MAXSIZE_TEMP_ARRAY(args, 1);
332  ADD_C(args, CSTR_AS_OBJ(server_addr));
333
334  push_call(ui, "connect", args);
335}
336
337// TODO(bfredl): use me to detach a specific ui from the server
338void remote_ui_stop(RemoteUI *ui)
339{
340}
341
342void nvim_ui_try_resize(uint64_t channel_id, Integer width, Integer height, Error *err)
343  FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
344{
345  RemoteUI *ui = get_ui_or_err(channel_id, err);
346  if (!ui) {
347    return;
348  }
349
350  if (width <= 0 || height <= 0) {
351    api_set_error(err, kErrorTypeValidation, "Expected width > 0 and height > 0");
352    return;
353  }
354
355  ui->width = (int)width;
356  ui->height = (int)height;
357  ui_refresh();
358}
359
360void nvim_ui_set_option(uint64_t channel_id, String name, Object value, Error *error)
361  FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
362{
363  RemoteUI *ui = get_ui_or_err(channel_id, error);
364  if (!ui) {
365    return;
366  }
367
368  ui_set_option(ui, false, name, value, error);
369}
370
371static void ui_set_option(RemoteUI *ui, bool init, String name, Object value, Error *err)
372{
373  if (strequal(name.data, "override")) {
374    VALIDATE_T("override", kObjectTypeBoolean, value.type, {
375      return;
376    });
377    ui->override = value.data.boolean;
378    return;
379  }
380
381  if (strequal(name.data, "rgb")) {
382    VALIDATE_T("rgb", kObjectTypeBoolean, value.type, {
383      return;
384    });
385    ui->rgb = value.data.boolean;
386    // A little drastic, but only takes effect for legacy uis. For linegrid UI
387    // only changes metadata for nvim_list_uis(), no refresh needed.
388    if (!init && !ui->ui_ext[kUILinegrid]) {
389      ui_refresh();
390    }
391    return;
392  }
393
394  if (strequal(name.data, "term_name")) {
395    VALIDATE_T("term_name", kObjectTypeString, value.type, {
396      return;
397    });
398    set_tty_option("term", string_to_cstr(value.data.string));
399    ui->term_name = string_to_cstr(value.data.string);
400    return;
401  }
402
403  if (strequal(name.data, "term_colors")) {
404    VALIDATE_T("term_colors", kObjectTypeInteger, value.type, {
405      return;
406    });
407    t_colors = (int)value.data.integer;
408    ui->term_colors = (int)value.data.integer;
409    return;
410  }
411
412  if (strequal(name.data, "stdin_fd")) {
413    VALIDATE_T("stdin_fd", kObjectTypeInteger, value.type, {
414      return;
415    });
416    VALIDATE_INT((value.data.integer >= 0), "stdin_fd", value.data.integer, {
417      return;
418    });
419    VALIDATE((starting == NO_SCREEN), "%s", "stdin_fd can only be used with first attached UI", {
420      return;
421    });
422
423    stdin_fd = (int)value.data.integer;
424    return;
425  }
426
427  if (strequal(name.data, "stdin_tty")) {
428    VALIDATE_T("stdin_tty", kObjectTypeBoolean, value.type, {
429      return;
430    });
431    if (ui->channel_id == CHAN_STDIO) {
432      stdin_isatty = value.data.boolean;
433    }
434    ui->stdin_tty = value.data.boolean;
435    return;
436  }
437
438  if (strequal(name.data, "stdout_tty")) {
439    VALIDATE_T("stdout_tty", kObjectTypeBoolean, value.type, {
440      return;
441    });
442    if (ui->channel_id == CHAN_STDIO) {
443      stdout_isatty = value.data.boolean;
444    }
445    ui->stdout_tty = value.data.boolean;
446    return;
447  }
448
449  // LEGACY: Deprecated option, use `ext_cmdline` instead.
450  bool is_popupmenu = strequal(name.data, "popupmenu_external");
451
452  for (UIExtension i = 0; i < kUIExtCount; i++) {
453    if (strequal(name.data, ui_ext_names[i])
454        || (i == kUIPopupmenu && is_popupmenu)) {
455      VALIDATE_EXP((value.type == kObjectTypeBoolean), name.data, "Boolean",
456                   api_typename(value.type), {
457        return;
458      });
459      bool boolval = value.data.boolean;
460      if (!init && i == kUILinegrid && boolval != ui->ui_ext[i]) {
461        // There shouldn't be a reason for a UI to do this ever
462        // so explicitly don't support this.
463        api_set_error(err, kErrorTypeValidation, "ext_linegrid option cannot be changed");
464      }
465      ui->ui_ext[i] = boolval;
466      if (!init) {
467        ui_set_ext_option(ui, i, boolval);
468      }
469      return;
470    }
471  }
472
473  VALIDATE_S(false, "UI option", name.data, {
474    return;
475  });
476}
477
478/// Tell Nvim to resize a grid. Triggers a grid_resize event with the requested
479/// grid size or the maximum size if it exceeds size limits.
480///
481/// On invalid grid handle, fails with error.
482///
483/// @param channel_id
484/// @param grid    The handle of the grid to be changed.
485/// @param width   The new requested width.
486/// @param height  The new requested height.
487/// @param[out] err Error details, if any
488void nvim_ui_try_resize_grid(uint64_t channel_id, Integer grid, Integer width, Integer height,
489                             Error *err)
490  FUNC_API_SINCE(6) FUNC_API_REMOTE_ONLY
491{
492  if (!get_ui_or_err(channel_id, err)) {
493    return;
494  }
495
496  if (grid == DEFAULT_GRID_HANDLE) {
497    nvim_ui_try_resize(channel_id, width, height, err);
498  } else {
499    ui_grid_resize((handle_T)grid, (int)width, (int)height, err);
500  }
501}
502
503/// Tells Nvim the number of elements displaying in the popupmenu, to decide
504/// [<PageUp>] and [<PageDown>] movement.
505///
506/// @param channel_id
507/// @param height  Popupmenu height, must be greater than zero.
508/// @param[out] err Error details, if any
509void nvim_ui_pum_set_height(uint64_t channel_id, Integer height, Error *err)
510  FUNC_API_SINCE(6) FUNC_API_REMOTE_ONLY
511{
512  RemoteUI *ui = get_ui_or_err(channel_id, err);
513  if (!ui) {
514    return;
515  }
516
517  if (height <= 0) {
518    api_set_error(err, kErrorTypeValidation, "Expected pum height > 0");
519    return;
520  }
521
522  if (!ui->ui_ext[kUIPopupmenu]) {
523    api_set_error(err, kErrorTypeValidation, "UI must support the ext_popupmenu option");
524    return;
525  }
526
527  ui->pum_nlines = (int)height;
528}
529
530/// Tells Nvim the geometry of the popupmenu, to align floating windows with an
531/// external popup menu.
532///
533/// Note that this method is not to be confused with |nvim_ui_pum_set_height()|,
534/// which sets the number of visible items in the popup menu, while this
535/// function sets the bounding box of the popup menu, including visual
536/// elements such as borders and sliders. Floats need not use the same font
537/// size, nor be anchored to exact grid corners, so one can set floating-point
538/// numbers to the popup menu geometry.
539///
540/// @param channel_id
541/// @param width   Popupmenu width.
542/// @param height  Popupmenu height.
543/// @param row     Popupmenu row.
544/// @param col     Popupmenu height.
545/// @param[out] err Error details, if any.
546void nvim_ui_pum_set_bounds(uint64_t channel_id, Float width, Float height, Float row, Float col,
547                            Error *err)
548  FUNC_API_SINCE(7) FUNC_API_REMOTE_ONLY
549{
550  RemoteUI *ui = get_ui_or_err(channel_id, err);
551  if (!ui) {
552    return;
553  }
554
555  if (!ui->ui_ext[kUIPopupmenu]) {
556    api_set_error(err, kErrorTypeValidation,
557                  "UI must support the ext_popupmenu option");
558    return;
559  }
560
561  if (width <= 0) {
562    api_set_error(err, kErrorTypeValidation, "Expected width > 0");
563    return;
564  } else if (height <= 0) {
565    api_set_error(err, kErrorTypeValidation, "Expected height > 0");
566    return;
567  }
568
569  ui->pum_row = (double)row;
570  ui->pum_col = (double)col;
571  ui->pum_width = (double)width;
572  ui->pum_height = (double)height;
573  ui->pum_pos = true;
574}
575
576static void flush_event(RemoteUI *ui)
577{
578  if (ui->cur_event) {
579    mpack_w2(&ui->ncalls_pos, 1 + ui->ncalls);
580    ui->cur_event = NULL;
581    ui->ncalls_pos = NULL;
582    ui->ncalls = 0;
583  }
584}
585
586static void ui_alloc_buf(RemoteUI *ui)
587{
588  ui->packer.startptr = alloc_block();
589  ui->packer.ptr = ui->packer.startptr;
590  ui->packer.endptr = ui->packer.startptr + UI_BUF_SIZE;
591}
592
593static void prepare_call(RemoteUI *ui, const char *name)
594{
595  if (ui->packer.startptr
596      && (BUF_POS(ui) > UI_BUF_SIZE - EVENT_BUF_SIZE || ui->ncells_pending >= 500)) {
597    ui_flush_buf(ui, false);
598  }
599
600  if (ui->packer.startptr == NULL) {
601    ui_alloc_buf(ui);
602  }
603
604  // To optimize data transfer (especially for "grid_line"), we bundle adjacent
605  // calls to same method together, so only add a new call entry if the last
606  // method call is different from "name"
607
608  if (!ui->cur_event || !strequal(ui->cur_event, name)) {
609    char **buf = &ui->packer.ptr;
610    if (!ui->nevents_pos) {
611      // [2, "redraw", [...]]
612      mpack_array(buf, 3);
613      mpack_uint(buf, 2);
614      mpack_str_small(buf, S_LEN("redraw"));
615      ui->nevents_pos = mpack_array_dyn16(buf);
616      assert(ui->cur_event == NULL);
617    }
618    flush_event(ui);
619    ui->cur_event = name;
620    ui->ncalls_pos = mpack_array_dyn16(buf);
621    mpack_str_small(buf, name, strlen(name));
622    ui->nevents++;
623    ui->ncalls = 1;
624  } else {
625    ui->ncalls++;
626  }
627}
628
629/// Pushes data into RemoteUI, to be consumed later by remote_ui_flush().
630static void push_call(RemoteUI *ui, const char *name, Array args)
631{
632  prepare_call(ui, name);
633  mpack_object_array(args, &ui->packer);
634}
635
636static void ui_flush_callback(PackerBuffer *packer)
637{
638  RemoteUI *ui = packer->anydata;
639  ui_flush_buf(ui, true);
640  ui_alloc_buf(ui);
641}
642
643void remote_ui_grid_clear(RemoteUI *ui, Integer grid)
644{
645  MAXSIZE_TEMP_ARRAY(args, 1);
646  if (ui->ui_ext[kUILinegrid]) {
647    ADD_C(args, INTEGER_OBJ(grid));
648  }
649  const char *name = ui->ui_ext[kUILinegrid] ? "grid_clear" : "clear";
650  push_call(ui, name, args);
651}
652
653void remote_ui_grid_resize(RemoteUI *ui, Integer grid, Integer width, Integer height)
654{
655  MAXSIZE_TEMP_ARRAY(args, 3);
656  if (ui->ui_ext[kUILinegrid]) {
657    ADD_C(args, INTEGER_OBJ(grid));
658  } else {
659    ui->client_col = -1;  // force cursor update
660  }
661  ADD_C(args, INTEGER_OBJ(width));
662  ADD_C(args, INTEGER_OBJ(height));
663  const char *name = ui->ui_ext[kUILinegrid] ? "grid_resize" : "resize";
664  push_call(ui, name, args);
665}
666
667void remote_ui_grid_scroll(RemoteUI *ui, Integer grid, Integer top, Integer bot, Integer left,
668                           Integer right, Integer rows, Integer cols)
669{
670  if (ui->ui_ext[kUILinegrid]) {
671    MAXSIZE_TEMP_ARRAY(args, 7);
672    ADD_C(args, INTEGER_OBJ(grid));
673    ADD_C(args, INTEGER_OBJ(top));
674    ADD_C(args, INTEGER_OBJ(bot));
675    ADD_C(args, INTEGER_OBJ(left));
676    ADD_C(args, INTEGER_OBJ(right));
677    ADD_C(args, INTEGER_OBJ(rows));
678    ADD_C(args, INTEGER_OBJ(cols));
679    push_call(ui, "grid_scroll", args);
680  } else {
681    MAXSIZE_TEMP_ARRAY(args, 4);
682    ADD_C(args, INTEGER_OBJ(top));
683    ADD_C(args, INTEGER_OBJ(bot - 1));
684    ADD_C(args, INTEGER_OBJ(left));
685    ADD_C(args, INTEGER_OBJ(right - 1));
686    push_call(ui, "set_scroll_region", args);
687
688    kv_size(args) = 0;
689    ADD_C(args, INTEGER_OBJ(rows));
690    push_call(ui, "scroll", args);
691
692    // some clients have "clear" being affected by scroll region, so reset it.
693    kv_size(args) = 0;
694    ADD_C(args, INTEGER_OBJ(0));
695    ADD_C(args, INTEGER_OBJ(ui->height - 1));
696    ADD_C(args, INTEGER_OBJ(0));
697    ADD_C(args, INTEGER_OBJ(ui->width - 1));
698    push_call(ui, "set_scroll_region", args);
699  }
700}
701
702void remote_ui_default_colors_set(RemoteUI *ui, Integer rgb_fg, Integer rgb_bg, Integer rgb_sp,
703                                  Integer cterm_fg, Integer cterm_bg)
704{
705  if (!ui->ui_ext[kUITermColors]) {
706    HL_SET_DEFAULT_COLORS(rgb_fg, rgb_bg, rgb_sp);
707  }
708  MAXSIZE_TEMP_ARRAY(args, 5);
709  ADD_C(args, INTEGER_OBJ(rgb_fg));
710  ADD_C(args, INTEGER_OBJ(rgb_bg));
711  ADD_C(args, INTEGER_OBJ(rgb_sp));
712  ADD_C(args, INTEGER_OBJ(cterm_fg));
713  ADD_C(args, INTEGER_OBJ(cterm_bg));
714  push_call(ui, "default_colors_set", args);
715
716  // Deprecated
717  if (!ui->ui_ext[kUILinegrid]) {
718    kv_size(args) = 0;
719    ADD_C(args, INTEGER_OBJ(ui->rgb ? rgb_fg : cterm_fg - 1));
720    push_call(ui, "update_fg", args);
721
722    kv_size(args) = 0;
723    ADD_C(args, INTEGER_OBJ(ui->rgb ? rgb_bg : cterm_bg - 1));
724    push_call(ui, "update_bg", args);
725
726    kv_size(args) = 0;
727    ADD_C(args, INTEGER_OBJ(ui->rgb ? rgb_sp : -1));
728    push_call(ui, "update_sp", args);
729  }
730}
731
732void remote_ui_hl_attr_define(RemoteUI *ui, Integer id, HlAttrs rgb_attrs, HlAttrs cterm_attrs,
733                              Array info)
734{
735  if (!ui->ui_ext[kUILinegrid]) {
736    return;
737  }
738
739  MAXSIZE_TEMP_ARRAY(args, 4);
740  ADD_C(args, INTEGER_OBJ(id));
741  MAXSIZE_TEMP_DICT(rgb, HLATTRS_DICT_SIZE);
742  MAXSIZE_TEMP_DICT(cterm, HLATTRS_DICT_SIZE);
743  hlattrs2dict(&rgb, NULL, rgb_attrs, true, false);
744  hlattrs2dict(&cterm, NULL, rgb_attrs, false, false);
745
746  // URLs are not added in hlattrs2dict since they are used only by UIs and not by the highlight
747  // system. So we add them here.
748  if (rgb_attrs.url >= 0) {
749    const char *url = hl_get_url((uint32_t)rgb_attrs.url);
750    PUT_C(rgb, "url", CSTR_AS_OBJ(url));
751  }
752
753  ADD_C(args, DICT_OBJ(rgb));
754  ADD_C(args, DICT_OBJ(cterm));
755
756  if (ui->ui_ext[kUIHlState]) {
757    ADD_C(args, ARRAY_OBJ(info));
758  } else {
759    ADD_C(args, ARRAY_OBJ((Array)ARRAY_DICT_INIT));
760  }
761
762  push_call(ui, "hl_attr_define", args);
763}
764
765void remote_ui_highlight_set(RemoteUI *ui, int id)
766{
767  if (ui->hl_id == id) {
768    return;
769  }
770
771  ui->hl_id = id;
772  MAXSIZE_TEMP_DICT(dict, HLATTRS_DICT_SIZE);
773  hlattrs2dict(&dict, NULL, syn_attr2entry(id), ui->rgb, false);
774  MAXSIZE_TEMP_ARRAY(args, 1);
775  ADD_C(args, DICT_OBJ(dict));
776  push_call(ui, "highlight_set", args);
777}
778
779/// "true" cursor used only for input focus
780void remote_ui_grid_cursor_goto(RemoteUI *ui, Integer grid, Integer row, Integer col)
781{
782  if (ui->ui_ext[kUILinegrid]) {
783    MAXSIZE_TEMP_ARRAY(args, 3);
784    ADD_C(args, INTEGER_OBJ(grid));
785    ADD_C(args, INTEGER_OBJ(row));
786    ADD_C(args, INTEGER_OBJ(col));
787    push_call(ui, "grid_cursor_goto", args);
788  } else {
789    ui->cursor_row = row;
790    ui->cursor_col = col;
791    remote_ui_cursor_goto(ui, row, col);
792  }
793}
794
795/// emulated cursor used both for drawing and for input focus
796void remote_ui_cursor_goto(RemoteUI *ui, Integer row, Integer col)
797{
798  if (ui->client_row == row && ui->client_col == col) {
799    return;
800  }
801  ui->client_row = row;
802  ui->client_col = col;
803  MAXSIZE_TEMP_ARRAY(args, 2);
804  ADD_C(args, INTEGER_OBJ(row));
805  ADD_C(args, INTEGER_OBJ(col));
806  push_call(ui, "cursor_goto", args);
807}
808
809void remote_ui_put(RemoteUI *ui, const char *cell)
810{
811  ui->client_col++;
812  MAXSIZE_TEMP_ARRAY(args, 1);
813  ADD_C(args, CSTR_AS_OBJ(cell));
814  push_call(ui, "put", args);
815}
816
817void remote_ui_raw_line(RemoteUI *ui, Integer grid, Integer row, Integer startcol, Integer endcol,
818                        Integer clearcol, Integer clearattr, LineFlags flags, const schar_T *chunk,
819                        const sattr_T *attrs)
820{
821  // If MAX_SCHAR_SIZE is made larger, we need to refactor implementation below
822  // to not only use FIXSTR (only up to 0x20 bytes)
823  STATIC_ASSERT(MAX_SCHAR_SIZE - 1 < 0x20, "SCHAR doesn't fit in fixstr");
824
825  if (ui->ui_ext[kUILinegrid]) {
826    prepare_call(ui, "grid_line");
827
828    char **buf = &ui->packer.ptr;
829    mpack_array(buf, 5);
830    mpack_uint(buf, (uint32_t)grid);
831    mpack_uint(buf, (uint32_t)row);
832    mpack_uint(buf, (uint32_t)startcol);
833    char *lenpos = mpack_array_dyn16(buf);
834
835    uint32_t repeat = 0;
836    size_t ncells = (size_t)(endcol - startcol);
837    int last_hl = -1;
838    uint32_t nelem = 0;
839    bool was_space = false;
840    for (size_t i = 0; i < ncells; i++) {
841      repeat++;
842      if (i == ncells - 1 || attrs[i] != attrs[i + 1] || chunk[i] != chunk[i + 1]) {
843        if (
844            // Close to overflowing the redraw buffer. Finish this event, flush,
845            // and start a new "grid_line" event at the current position.
846            // For simplicity leave place for the final "clear" element as well,
847            // hence the factor of 2 in the check.
848            UI_BUF_SIZE - BUF_POS(ui) < 2 * (1 + 2 + MAX_SCHAR_SIZE + 5 + 5) + 1
849            // Also if there is a lot of packed cells, pass them off to the UI to
850            // let it start processing them.
851            || ui->ncells_pending >= 500) {
852          // If the last chunk was all spaces, add an empty clearing chunk,
853          // so it's clear that the last chunk wasn't a clearing chunk.
854          if (was_space) {
855            nelem++;
856            ui->ncells_pending += 1;
857            mpack_array(buf, 3);
858            mpack_str_small(buf, S_LEN(" "));
859            mpack_uint(buf, (uint32_t)clearattr);
860            mpack_uint(buf, 0);
861          }
862          mpack_w2(&lenpos, nelem);
863          // We only ever set the wrap field on the final "grid_line" event for the line.
864          mpack_bool(buf, false);
865          ui_flush_buf(ui, false);
866
867          prepare_call(ui, "grid_line");
868          mpack_array(buf, 5);
869          mpack_uint(buf, (uint32_t)grid);
870          mpack_uint(buf, (uint32_t)row);
871          mpack_uint(buf, (uint32_t)startcol + (uint32_t)i - repeat + 1);
872          lenpos = mpack_array_dyn16(buf);
873          nelem = 0;
874          last_hl = -1;
875        }
876        uint32_t csize = (repeat > 1) ? 3 : ((attrs[i] != last_hl) ? 2 : 1);
877        nelem++;
878        mpack_array(buf, csize);
879        char *size_byte = (*buf)++;
880        size_t len = schar_get_adv(buf, chunk[i]);
881        *size_byte = (char)(0xa0 | len);
882        if (csize >= 2) {
883          mpack_uint(buf, (uint32_t)attrs[i]);
884          if (csize >= 3) {
885            mpack_uint(buf, repeat);
886          }
887        }
888        ui->ncells_pending += MIN(repeat, 2);
889        last_hl = attrs[i];
890        repeat = 0;
891        was_space = chunk[i] == schar_from_ascii(' ');
892      }
893    }
894    // If the last chunk was all spaces, add a clearing chunk even if there are
895    // no more cells to clear, so there is no ambiguity about what to clear.
896    if (endcol < clearcol || was_space) {
897      nelem++;
898      ui->ncells_pending += 1;
899      mpack_array(buf, 3);
900      mpack_str_small(buf, S_LEN(" "));
901      mpack_uint(buf, (uint32_t)clearattr);
902      mpack_uint(buf, (uint32_t)(clearcol - endcol));
903    }
904    mpack_w2(&lenpos, nelem);
905    mpack_bool(buf, flags & kLineFlagWrap);
906  } else {
907    for (int i = 0; i < endcol - startcol; i++) {
908      remote_ui_cursor_goto(ui, row, startcol + i);
909      remote_ui_highlight_set(ui, attrs[i]);
910      char sc_buf[MAX_SCHAR_SIZE];
911      schar_get(sc_buf, chunk[i]);
912      remote_ui_put(ui, sc_buf);
913      if (utf_ambiguous_width(sc_buf)) {
914        ui->client_col = -1;  // force cursor update
915      }
916    }
917    if (endcol < clearcol) {
918      remote_ui_cursor_goto(ui, row, endcol);
919      remote_ui_highlight_set(ui, (int)clearattr);
920      // legacy eol_clear was only ever used with cleared attributes
921      // so be on the safe side
922      if (clearattr == 0 && clearcol == Columns) {
923        Array args = ARRAY_DICT_INIT;
924        push_call(ui, "eol_clear", args);
925      } else {
926        for (Integer c = endcol; c < clearcol; c++) {
927          remote_ui_put(ui, " ");
928        }
929      }
930    }
931  }
932}
933
934/// Flush the internal packing buffer to the client.
935///
936/// This might happen multiple times before the actual ui_flush, if the
937/// total redraw size is large!
938static void ui_flush_buf(RemoteUI *ui, bool incomplete_event)
939{
940  if (!ui->packer.startptr || !BUF_POS(ui)) {
941    return;
942  }
943  ui->incomplete_event = incomplete_event;
944
945  flush_event(ui);
946  if (ui->nevents_pos != NULL) {
947    mpack_w2(&ui->nevents_pos, ui->nevents);
948    ui->nevents = 0;
949    ui->nevents_pos = NULL;
950  }
951
952  WBuffer *buf = wstream_new_buffer(ui->packer.startptr, BUF_POS(ui), 1, free_block);
953  rpc_write_raw(ui->channel_id, buf);
954
955  ui->packer.startptr = NULL;
956  ui->packer.ptr = NULL;
957
958  // we have sent events to the client, but possibly not yet the final "flush" event.
959  ui->flushed_events = true;
960  ui->ncells_pending = 0;
961}
962
963/// An intentional flush (vsync) when Nvim is finished redrawing the screen
964///
965/// Clients can know this happened by a final "flush" event at the end of the
966/// "redraw" batch.
967void remote_ui_flush(RemoteUI *ui)
968{
969  if (ui->nevents > 0 || ui->flushed_events) {
970    if (!ui->ui_ext[kUILinegrid]) {
971      remote_ui_cursor_goto(ui, ui->cursor_row, ui->cursor_col);
972    }
973    push_call(ui, "flush", (Array)ARRAY_DICT_INIT);
974    ui_flush_buf(ui, false);
975    ui->flushed_events = false;
976  }
977}
978
979void remote_ui_ui_send(RemoteUI *ui, String content)
980{
981  if (!ui->stdout_tty) {
982    return;
983  }
984
985  MAXSIZE_TEMP_ARRAY(args, 1);
986  ADD_C(args, STRING_OBJ(content));
987  push_call(ui, "ui_send", args);
988}
989
990void remote_ui_flush_pending_data(RemoteUI *ui)
991{
992  ui_flush_buf(ui, false);
993}
994
995static Array translate_contents(RemoteUI *ui, Array contents, Arena *arena)
996{
997  Array new_contents = arena_array(arena, contents.size);
998  for (size_t i = 0; i < contents.size; i++) {
999    Array item = contents.items[i].data.array;
1000    Array new_item = arena_array(arena, 2);
1001    int attr = (int)item.items[0].data.integer;
1002    if (attr) {
1003      Dict rgb_attrs = arena_dict(arena, HLATTRS_DICT_SIZE);
1004      hlattrs2dict(&rgb_attrs, NULL, syn_attr2entry(attr), ui->rgb, false);
1005      ADD_C(new_item, DICT_OBJ(rgb_attrs));
1006    } else {
1007      ADD_C(new_item, DICT_OBJ((Dict)ARRAY_DICT_INIT));
1008    }
1009    ADD_C(new_item, item.items[1]);
1010    ADD_C(new_contents, ARRAY_OBJ(new_item));
1011  }
1012  return new_contents;
1013}
1014
1015static Array translate_firstarg(RemoteUI *ui, Array args, Arena *arena)
1016{
1017  Array new_args = arena_array(arena, args.size);
1018  Array contents = args.items[0].data.array;
1019
1020  ADD_C(new_args, ARRAY_OBJ(translate_contents(ui, contents, arena)));
1021  for (size_t i = 1; i < args.size; i++) {
1022    ADD_C(new_args, args.items[i]);
1023  }
1024  return new_args;
1025}
1026
1027void remote_ui_event(RemoteUI *ui, char *name, Array args)
1028{
1029  Arena arena = ARENA_EMPTY;
1030  if (!ui->ui_ext[kUILinegrid]) {
1031    // the representation of highlights in cmdline changed, translate back
1032    // never consumes args
1033    if (strequal(name, "cmdline_show")) {
1034      Array new_args = translate_firstarg(ui, args, &arena);
1035      push_call(ui, name, new_args);
1036      goto free_ret;
1037    } else if (strequal(name, "cmdline_block_show")) {
1038      Array block = args.items[0].data.array;
1039      Array new_block = arena_array(&arena, block.size);
1040      for (size_t i = 0; i < block.size; i++) {
1041        ADD_C(new_block, ARRAY_OBJ(translate_contents(ui, block.items[i].data.array, &arena)));
1042      }
1043      MAXSIZE_TEMP_ARRAY(new_args, 1);
1044      ADD_C(new_args, ARRAY_OBJ(new_block));
1045      push_call(ui, name, new_args);
1046      goto free_ret;
1047    } else if (strequal(name, "cmdline_block_append")) {
1048      Array new_args = translate_firstarg(ui, args, &arena);
1049      push_call(ui, name, new_args);
1050      goto free_ret;
1051    }
1052  }
1053
1054  // Back-compat: translate popupmenu_xx to legacy wildmenu_xx.
1055  if (ui->ui_ext[kUIWildmenu]) {
1056    if (strequal(name, "popupmenu_show")) {
1057      ui->wildmenu_active = (args.items[4].data.integer == -1)
1058                            || !ui->ui_ext[kUIPopupmenu];
1059      if (ui->wildmenu_active) {
1060        Array items = args.items[0].data.array;
1061        Array new_items = arena_array(&arena, items.size);
1062        for (size_t i = 0; i < items.size; i++) {
1063          ADD_C(new_items, items.items[i].data.array.items[0]);
1064        }
1065        MAXSIZE_TEMP_ARRAY(new_args, 1);
1066        ADD_C(new_args, ARRAY_OBJ(new_items));
1067        push_call(ui, "wildmenu_show", new_args);
1068        if (args.items[1].data.integer != -1) {
1069          kv_size(new_args) = 0;
1070          ADD_C(new_args, args.items[1]);
1071          push_call(ui, "wildmenu_select", new_args);
1072        }
1073        goto free_ret;
1074      }
1075    } else if (strequal(name, "popupmenu_select")) {
1076      if (ui->wildmenu_active) {
1077        name = "wildmenu_select";
1078      }
1079    } else if (strequal(name, "popupmenu_hide")) {
1080      if (ui->wildmenu_active) {
1081        name = "wildmenu_hide";
1082      }
1083    }
1084  }
1085
1086  push_call(ui, name, args);
1087  return;
1088
1089free_ret:
1090  arena_mem_free(arena_finish(&arena));
1091}
1092
1093/// Sends arbitrary data to a UI. Use this instead of |nvim_chan_send()| or `io.stdout:write()`, if
1094/// you really want to write to the |TUI| host terminal.
1095///
1096/// Emits a "ui_send" event to all UIs with the "stdout_tty" |ui-option| set. UIs are expected to
1097/// write the received data to a connected TTY if one exists.
1098///
1099/// @param channel_id
1100/// @param content Content to write to the TTY
1101/// @param[out] err Error details, if any
1102void nvim_ui_send(uint64_t channel_id, String content, Error *err)
1103  FUNC_API_SINCE(14)
1104{
1105  ui_call_ui_send(content);
1106}