robin/laufey

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

Justin M. Keyesfix(:restart): set job env instead of mutating parent env #40308a1da5d1f14

master
12.5 KiB425 linesraw
1/// Nvim's own UI client, which attaches to a child or remote Nvim server.
2
3#include <assert.h>
4#include <stdbool.h>
5#include <stdint.h>
6#include <stdlib.h>
7
8#include "nvim/api/keysets_defs.h"
9#include "nvim/api/private/defs.h"
10#include "nvim/api/private/helpers.h"
11#include "nvim/channel.h"
12#include "nvim/channel_defs.h"
13#include "nvim/eval/typval_defs.h"
14#include "nvim/event/multiqueue.h"
15#include "nvim/event/socket.h"
16#include "nvim/globals.h"
17#include "nvim/highlight.h"
18#include "nvim/highlight_defs.h"
19#include "nvim/log.h"
20#include "nvim/main.h"
21#include "nvim/memory.h"
22#include "nvim/memory_defs.h"
23#include "nvim/msgpack_rpc/channel.h"
24#include "nvim/msgpack_rpc/channel_defs.h"
25#include "nvim/os/os.h"
26#include "nvim/profile.h"
27#include "nvim/tui/tui.h"
28#include "nvim/tui/tui_defs.h"
29#include "nvim/ui.h"
30#include "nvim/ui_client.h"
31#include "nvim/ui_defs.h"
32
33#ifdef MSWIN
34# include "nvim/os/os_win_console.h"
35#endif
36
37static TUIData *tui = NULL;
38static int tui_width = 0;
39static int tui_height = 0;
40static char *tui_term = "";
41static bool tui_rgb = false;
42
43// uncrustify:off
44#include "ui_client.c.generated.h"
45#include "ui_events_client.generated.h"
46// uncrustify:on
47
48uint64_t ui_client_start_server(const char *exepath, size_t argc, char **argv)
49{
50  char **args = xmalloc((2 + argc) * sizeof(char *));
51  int args_idx = 0;
52  args[args_idx++] = xstrdup(argv[0]);
53  args[args_idx++] = xstrdup("--embed");
54  for (size_t i = 1; i < argc; i++) {
55    args[args_idx++] = xstrdup(argv[i]);
56  }
57  args[args_idx++] = NULL;
58
59  CallbackReader on_err = CALLBACK_READER_INIT;
60  on_err.fwd_err = true;
61
62  bool detach = true;
63  varnumber_T exit_status;
64  Channel *channel = channel_job_start(args, exepath,
65                                       CALLBACK_READER_INIT, on_err, CALLBACK_NONE,
66                                       false, true, true, detach, kChannelStdinPipe,
67                                       NULL, 0, 0, NULL, &exit_status);
68  if (!channel) {
69    return 0;
70  }
71
72  // If stdin is not a pty, it is forwarded to the client.
73  // Replace stdin in the TUI process with the tty fd.
74  if (ui_client_forward_stdin) {
75    close(0);
76#ifdef MSWIN
77    os_open_conin_fd();
78#else
79    dup(stderr_isatty ? STDERR_FILENO : STDOUT_FILENO);
80#endif
81  }
82
83  return channel->id;
84}
85
86/// Attaches this client to the UI channel, and sets its client info.
87void ui_client_attach(int width, int height, char *term, bool rgb)
88{
89  //
90  // nvim_ui_attach
91  //
92  MAXSIZE_TEMP_ARRAY(args, 3);
93  ADD_C(args, INTEGER_OBJ(width));
94  ADD_C(args, INTEGER_OBJ(height));
95  MAXSIZE_TEMP_DICT(opts, 9);
96  PUT_C(opts, "rgb", BOOLEAN_OBJ(rgb));
97  PUT_C(opts, "ext_linegrid", BOOLEAN_OBJ(true));
98  PUT_C(opts, "ext_termcolors", BOOLEAN_OBJ(true));
99  if (term) {
100    PUT_C(opts, "term_name", CSTR_AS_OBJ(term));
101  }
102  PUT_C(opts, "term_colors", INTEGER_OBJ(t_colors));
103  PUT_C(opts, "stdin_tty", BOOLEAN_OBJ(stdin_isatty));
104  PUT_C(opts, "stdout_tty", BOOLEAN_OBJ(stdout_isatty));
105  if (ui_client_forward_stdin) {
106    PUT_C(opts, "stdin_fd", INTEGER_OBJ(UI_CLIENT_STDIN_FD));
107    ui_client_forward_stdin = false;  // stdin shouldn't be forwarded again #22292
108  }
109  ADD_C(args, DICT_OBJ(opts));
110
111  rpc_send_event(ui_client_channel_id, "nvim_ui_attach", args);
112  ui_client_attached = true;
113
114  TIME_MSG("nvim_ui_attach");
115
116  //
117  // nvim_set_client_info
118  //
119  MAXSIZE_TEMP_ARRAY(args2, 5);
120  ADD_C(args2, CSTR_AS_OBJ("nvim-tui"));            // name
121  Object m = api_metadata();
122  Dict version = { 0 };
123  assert(m.data.dict.size > 0);
124  for (size_t i = 0; i < m.data.dict.size; i++) {
125    if (strequal(m.data.dict.items[i].key.data, "version")) {
126      version = m.data.dict.items[i].value.data.dict;
127      break;
128    } else if (i + 1 == m.data.dict.size) {
129      abort();
130    }
131  }
132  ADD_C(args2, DICT_OBJ(version));                  // version
133  ADD_C(args2, CSTR_AS_OBJ("ui"));                  // type
134  // We don't send api_metadata.functions as the "methods" because:
135  // 1. it consumes memory.
136  // 2. it is unlikely to be useful, since the peer can just call `nvim_get_api`.
137  // 3. nvim_set_client_info expects a dict instead of an array.
138  ADD_C(args2, ARRAY_OBJ((Array)ARRAY_DICT_INIT));  // methods
139  MAXSIZE_TEMP_DICT(info, 9);                       // attributes
140  PUT_C(info, "website", CSTR_AS_OBJ("https://neovim.io"));
141  PUT_C(info, "license", CSTR_AS_OBJ("Apache 2"));
142  PUT_C(info, "pid", INTEGER_OBJ(os_get_pid()));
143  ADD_C(args2, DICT_OBJ(info));               // attributes
144  rpc_send_event(ui_client_channel_id, "nvim_set_client_info", args2);
145
146  TIME_MSG("nvim_set_client_info");
147}
148
149void ui_client_detach(void)
150{
151  rpc_send_event(ui_client_channel_id, "nvim_ui_detach", (Array)ARRAY_DICT_INIT);
152  ui_client_attached = false;
153}
154
155void ui_client_run(void)
156  FUNC_ATTR_NORETURN
157{
158  tui_start(&tui, &tui_width, &tui_height, &tui_term, &tui_rgb);
159  ui_client_attach(tui_width, tui_height, tui_term, tui_rgb);
160
161  // TODO(justinmk): this is for log_spec. Can remove this after nvim_log #7062 is merged.
162  if (os_env_exists(ENV_TEST_LOG, true)) {
163    ELOG("test log message");
164  }
165
166  time_finish();
167
168  // os_exit() will be invoked when the client channel detaches
169  while (true) {
170    // Need to process main_loop.events,
171    // otherwise channels closed due to server restart are never freed.
172    LOOP_PROCESS_EVENTS(&main_loop, main_loop.events, -1);
173  }
174}
175
176void ui_client_stop(void)
177{
178  ui_client_attached = false;
179  if (!tui_is_stopped(tui)) {
180    tui_stop(tui);
181  }
182}
183
184void ui_client_set_size(int width, int height)
185{
186  // The currently known size will be sent when attaching
187  if (ui_client_attached) {
188    MAXSIZE_TEMP_ARRAY(args, 2);
189    ADD_C(args, INTEGER_OBJ((int)width));
190    ADD_C(args, INTEGER_OBJ((int)height));
191    rpc_send_event(ui_client_channel_id, "nvim_ui_try_resize", args);
192  }
193  tui_width = width;
194  tui_height = height;
195}
196
197UIClientHandler ui_client_get_redraw_handler(const char *name, size_t name_len, Error *error)
198{
199  int hash = ui_client_handler_hash(name, name_len);
200  if (hash < 0) {
201    return (UIClientHandler){ NULL, NULL };
202  }
203  return event_handlers[hash];
204}
205
206/// Placeholder for _sync_ requests with 'redraw' method name
207///
208/// async 'redraw' events, which are expected when nvim acts as a ui client.
209/// get handled in msgpack_rpc/unpacker.c and directly dispatched to handlers
210/// of specific ui events, like ui_client_event_grid_resize and so on.
211Object handle_ui_client_redraw(uint64_t channel_id, Array args, Arena *arena, Error *error)
212{
213  api_set_error(error, kErrorTypeValidation, "'redraw' cannot be sent as a request");
214  return NIL;
215}
216
217static HlAttrs ui_client_dict2hlattrs(Dict d, bool rgb)
218{
219  Error err = ERROR_INIT;
220  Dict(highlight) dict = KEYDICT_INIT;
221  if (!api_dict_to_keydict(&dict, DictHash(highlight), d, &err)) {
222    // TODO(bfredl): log "err"
223    return HLATTRS_INIT;
224  }
225
226  HlAttrs attrs = dict2hlattrs(&dict, rgb, NULL, NULL, &err);
227
228  if (HAS_KEY(&dict, highlight, url)) {
229    attrs.url = tui_add_url(tui, dict.url.data);
230  }
231
232  return attrs;
233}
234
235void ui_client_event_grid_resize(Array args)
236{
237  if (args.size < 3
238      || args.items[0].type != kObjectTypeInteger
239      || args.items[1].type != kObjectTypeInteger
240      || args.items[2].type != kObjectTypeInteger) {
241    ELOG("Error handling ui event 'grid_resize'");
242    return;
243  }
244
245  Integer grid = args.items[0].data.integer;
246  Integer width = args.items[1].data.integer;
247  Integer height = args.items[2].data.integer;
248  tui_grid_resize(tui, grid, width, height);
249
250  if (grid_line_buf_size < (size_t)width) {
251    xfree(grid_line_buf_char);
252    xfree(grid_line_buf_attr);
253    grid_line_buf_size = (size_t)width;
254    grid_line_buf_char = xmalloc(grid_line_buf_size * sizeof(schar_T));
255    grid_line_buf_attr = xmalloc(grid_line_buf_size * sizeof(sattr_T));
256  }
257}
258
259void ui_client_event_grid_line(Array args)
260  FUNC_ATTR_NORETURN
261{
262  abort();  // unreachable
263}
264
265void ui_client_event_raw_line(GridLineEvent *g)
266{
267  int grid = g->args[0];
268  int row = g->args[1];
269  int startcol = g->args[2];
270  Integer endcol = startcol + g->coloff;
271  Integer clearcol = endcol + g->clear_width;
272  LineFlags lineflags = g->wrap ? kLineFlagWrap : 0;
273
274  tui_raw_line(tui, grid, row, startcol, endcol, clearcol, g->cur_attr, lineflags,
275               (const schar_T *)grid_line_buf_char, grid_line_buf_attr);
276}
277
278/// Handles the "connect" ui-event.
279void ui_client_event_connect(Array args)
280{
281  if (args.size < 1 || args.items[0].type != kObjectTypeString) {
282    ELOG("Error handling UI event 'connect'");
283    return;
284  }
285
286  String s = args.items[0].data.string;
287  char *server_addr = xmemdupz(s.data, s.size);
288  multiqueue_put(main_loop.fast_events, channel_connect_event, server_addr);
289  // Set a dummy channel ID to prevent client exit when server detaches.
290  ui_client_channel_id = UINT64_MAX;
291}
292
293static void channel_connect_event(void **argv)
294{
295  char *server_addr = argv[0];
296
297  const char *err = "";
298  bool is_tcp = socket_address_tcp_host_end(server_addr) != NULL;
299  CallbackReader on_data = CALLBACK_READER_INIT;
300  uint64_t chan = channel_connect(is_tcp, server_addr, true, on_data, 50, &err);
301
302  if (!strequal(err, "")) {
303    ELOG("Cannot connect to server %s: %s", server_addr, err);
304    xfree(server_addr);
305    ui_client_exit_status = 1;
306    os_exit(1);
307  }
308
309  ui_client_channel_id = chan;
310  ui_client_attach(tui_width, tui_height, tui_term, tui_rgb);
311
312  ILOG("Connected to server %s on channel %" PRId64, server_addr, chan);
313  xfree(server_addr);
314}
315
316/// When a "restart" ui-event is received, its arguments are saved here when
317/// waiting for the server to exit.
318static Array restart_args = ARRAY_DICT_INIT;
319static bool restart_pending = false;
320
321// A server might indicate in advance how a new server should be restarted
322// in cases it crashes due to an unexpected error.
323static Array restart_args_after_crash_exit = ARRAY_DICT_INIT;
324
325/// Handles the "restart" ui-event.
326void ui_client_event_restart(Array args)
327{
328  // NB: don't send nvim_ui_detach to server, as it may have already exited.
329  // ui_client_detach();
330
331  // Save the arguments for ui_client_attach_to_restarted_server() later.
332  api_free_array(restart_args);
333  restart_args = copy_array(args, NULL);
334  restart_pending = true;
335}
336
337void ui_client_event__set_restart_on_crash_exit(Array args)
338{
339  // Save the arguments for ui_client_may_restart_server() later.
340  api_free_array(restart_args_after_crash_exit);
341  restart_args_after_crash_exit = copy_array(args, NULL);
342}
343
344/// Called during "restart" when the old server just exited.
345void ui_client_attach_to_restarted_server(bool error_restart)
346{
347  Array args = restart_args;
348  bool restart = false;
349  if (!restart_pending) {
350    if (error_restart && ui_client_error_exit == -1 && restart_args_after_crash_exit.size > 0) {
351      restart = true;
352      args = restart_args_after_crash_exit;
353    } else {
354      return;
355    }
356  }
357
358  restart_pending = false;
359
360  if (args.size < 1 || args.items[0].type != kObjectTypeString) {
361    ELOG("Error handling ui event 'restart'");
362    goto cleanup;
363  }
364
365  uint64_t chan_id;
366  const char *first_arg = args.items[0].data.string.data;
367  if (restart) {
368    if (args.size < 2 || args.items[1].type != kObjectTypeArray) {
369      ELOG("Error handling ui event 'restart'");
370      goto cleanup;
371    }
372    Array cmdargs = args.items[1].data.array;
373    char **argv = xcalloc(cmdargs.size + 1, sizeof(char *));
374    for (size_t i = 0; i < cmdargs.size; i++) {
375      if (cmdargs.items[i].type == kObjectTypeString) {
376        argv[i] = cmdargs.items[i].data.string.data;
377      }
378      if (argv[i] == NULL) {
379        argv[i] = "";
380      }
381    }
382    chan_id = ui_client_start_server(first_arg, cmdargs.size, argv);
383    xfree(argv);
384    ui_client_error_exit = -1;
385  } else {
386    bool is_tcp = socket_address_tcp_host_end(first_arg) != NULL;
387    const char *err = NULL;
388    chan_id = channel_connect(is_tcp, first_arg, true, CALLBACK_READER_INIT, 50, &err);
389    if (err != NULL) {
390      ELOG("cannot connect to server %s: %s", first_arg, err);
391      goto cleanup;
392    }
393  }
394
395  // Client-side server re-attach.
396  ui_client_channel_id = chan_id;
397  ui_client_attach(tui_width, tui_height, tui_term, tui_rgb);
398
399  ILOG("restarted server address=%s id=%" PRId64, first_arg, chan_id);
400cleanup:
401  api_free_array(restart_args);
402  restart_args = (Array)ARRAY_DICT_INIT;
403  api_free_array(restart_args_after_crash_exit);
404  restart_args_after_crash_exit = (Array)ARRAY_DICT_INIT;
405}
406
407/// Handles the "error_exit" ui-event.
408void ui_client_event_error_exit(Array args)
409{
410  if (args.size < 1
411      || args.items[0].type != kObjectTypeInteger) {
412    ELOG("Error handling ui event 'error_exit'");
413    return;
414  }
415  ui_client_error_exit = (int)args.items[0].data.integer;
416}
417
418#ifdef EXITFREE
419void ui_client_free_all_mem(void)
420{
421  tui_free_all_mem(tui);
422  xfree(grid_line_buf_char);
423  xfree(grid_line_buf_attr);
424}
425#endif