robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
a1da5d1f14
master
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{ 50char ** args = xmalloc ((2 + argc )* sizeof (char * )); 51int args_idx = 0 ; 52args [args_idx ++ ]= xstrdup (argv [0 ]); 53args [args_idx ++ ]= xstrdup ("--embed" ); 54for (size_t i = 1 ;i < argc ;i ++ ) { 55args [args_idx ++ ]= xstrdup (argv [i ]); 56 } 57args [args_idx ++ ]= NULL ; 58 59CallbackReader on_err = CALLBACK_READER_INIT ; 60on_err .fwd_err = true; 61 62bool detach = true; 63varnumber_T exit_status ; 64Channel * channel = channel_job_start (args ,exepath , 65CALLBACK_READER_INIT ,on_err ,CALLBACK_NONE , 66 false, true, true,detach ,kChannelStdinPipe , 67NULL ,0 ,0 ,NULL ,& exit_status ); 68if (!channel ) { 69return 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. 74if (ui_client_forward_stdin ) { 75close (0 ); 76#ifdef MSWIN 77os_open_conin_fd (); 78#else 79dup (stderr_isatty ?STDERR_FILENO :STDOUT_FILENO ); 80#endif 81 } 82 83return 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// 92MAXSIZE_TEMP_ARRAY (args ,3 ); 93ADD_C (args ,INTEGER_OBJ (width )); 94ADD_C (args ,INTEGER_OBJ (height )); 95MAXSIZE_TEMP_DICT (opts ,9 ); 96PUT_C (opts ,"rgb" ,BOOLEAN_OBJ (rgb )); 97PUT_C (opts ,"ext_linegrid" ,BOOLEAN_OBJ (true)); 98PUT_C (opts ,"ext_termcolors" ,BOOLEAN_OBJ (true)); 99if (term ) { 100PUT_C (opts ,"term_name" ,CSTR_AS_OBJ (term )); 101 } 102PUT_C (opts ,"term_colors" ,INTEGER_OBJ (t_colors )); 103PUT_C (opts ,"stdin_tty" ,BOOLEAN_OBJ (stdin_isatty )); 104PUT_C (opts ,"stdout_tty" ,BOOLEAN_OBJ (stdout_isatty )); 105if (ui_client_forward_stdin ) { 106PUT_C (opts ,"stdin_fd" ,INTEGER_OBJ (UI_CLIENT_STDIN_FD )); 107ui_client_forward_stdin = false;// stdin shouldn't be forwarded again #22292 108 } 109ADD_C (args ,DICT_OBJ (opts )); 110 111rpc_send_event (ui_client_channel_id ,"nvim_ui_attach" ,args ); 112ui_client_attached = true; 113 114TIME_MSG ("nvim_ui_attach" ); 115 116// 117// nvim_set_client_info 118// 119MAXSIZE_TEMP_ARRAY (args2 ,5 ); 120ADD_C (args2 ,CSTR_AS_OBJ ("nvim-tui" ));// name 121Object m = api_metadata (); 122Dict version = {0 }; 123assert (m .data .dict .size > 0 ); 124for (size_t i = 0 ;i < m .data .dict .size ;i ++ ) { 125if (strequal (m .data .dict .items [i ].key .data ,"version" )) { 126version = m .data .dict .items [i ].value .data .dict ; 127break ; 128 }else if (i + 1 == m .data .dict .size ) { 129abort (); 130 } 131 } 132ADD_C (args2 ,DICT_OBJ (version ));// version 133ADD_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. 138ADD_C (args2 ,ARRAY_OBJ ((Array )ARRAY_DICT_INIT ));// methods 139MAXSIZE_TEMP_DICT (info ,9 );// attributes 140PUT_C (info ,"website" ,CSTR_AS_OBJ ("https://neovim.io" )); 141PUT_C (info ,"license" ,CSTR_AS_OBJ ("Apache 2" )); 142PUT_C (info ,"pid" ,INTEGER_OBJ (os_get_pid ())); 143ADD_C (args2 ,DICT_OBJ (info ));// attributes 144rpc_send_event (ui_client_channel_id ,"nvim_set_client_info" ,args2 ); 145 146TIME_MSG ("nvim_set_client_info" ); 147} 148 149void ui_client_detach (void ) 150{ 151rpc_send_event (ui_client_channel_id ,"nvim_ui_detach" , (Array )ARRAY_DICT_INIT ); 152ui_client_attached = false; 153} 154 155void ui_client_run (void ) 156FUNC_ATTR_NORETURN 157{ 158tui_start (& tui ,& tui_width ,& tui_height ,& tui_term ,& tui_rgb ); 159ui_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. 162if (os_env_exists (ENV_TEST_LOG , true)) { 163ELOG ("test log message" ); 164 } 165 166time_finish (); 167 168// os_exit() will be invoked when the client channel detaches 169while (true) { 170// Need to process main_loop.events, 171// otherwise channels closed due to server restart are never freed. 172LOOP_PROCESS_EVENTS (& main_loop ,main_loop .events ,-1 ); 173 } 174} 175 176void ui_client_stop (void ) 177{ 178ui_client_attached = false; 179if (!tui_is_stopped (tui )) { 180tui_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 187if (ui_client_attached ) { 188MAXSIZE_TEMP_ARRAY (args ,2 ); 189ADD_C (args ,INTEGER_OBJ ((int )width )); 190ADD_C (args ,INTEGER_OBJ ((int )height )); 191rpc_send_event (ui_client_channel_id ,"nvim_ui_try_resize" ,args ); 192 } 193tui_width = width ; 194tui_height = height ; 195} 196 197UIClientHandler ui_client_get_redraw_handler (const char * name ,size_t name_len ,Error * error ) 198{ 199int hash = ui_client_handler_hash (name ,name_len ); 200if (hash < 0 ) { 201return (UIClientHandler ){NULL ,NULL }; 202 } 203return 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{ 213api_set_error (error ,kErrorTypeValidation ,"'redraw' cannot be sent as a request" ); 214return NIL ; 215} 216 217static HlAttrs ui_client_dict2hlattrs (Dict d ,bool rgb ) 218{ 219Error err = ERROR_INIT ; 220Dict (highlight )dict = KEYDICT_INIT ; 221if (!api_dict_to_keydict (& dict ,DictHash (highlight ),d ,& err )) { 222// TODO(bfredl): log "err" 223return HLATTRS_INIT ; 224 } 225 226HlAttrs attrs = dict2hlattrs (& dict ,rgb ,NULL ,NULL ,& err ); 227 228if (HAS_KEY (& dict ,highlight ,url )) { 229attrs .url = tui_add_url (tui ,dict .url .data ); 230 } 231 232return attrs ; 233} 234 235void ui_client_event_grid_resize (Array args ) 236{ 237if (args .size < 3 238|| args .items [0 ].type != kObjectTypeInteger 239|| args .items [1 ].type != kObjectTypeInteger 240|| args .items [2 ].type != kObjectTypeInteger ) { 241ELOG ("Error handling ui event 'grid_resize'" ); 242return ; 243 } 244 245Integer grid = args .items [0 ].data .integer ; 246Integer width = args .items [1 ].data .integer ; 247Integer height = args .items [2 ].data .integer ; 248tui_grid_resize (tui ,grid ,width ,height ); 249 250if (grid_line_buf_size < (size_t )width ) { 251xfree (grid_line_buf_char ); 252xfree (grid_line_buf_attr ); 253grid_line_buf_size = (size_t )width ; 254grid_line_buf_char = xmalloc (grid_line_buf_size * sizeof (schar_T )); 255grid_line_buf_attr = xmalloc (grid_line_buf_size * sizeof (sattr_T )); 256 } 257} 258 259void ui_client_event_grid_line (Array args ) 260FUNC_ATTR_NORETURN 261{ 262abort ();// unreachable 263} 264 265void ui_client_event_raw_line (GridLineEvent * g ) 266{ 267int grid = g -> args [0 ]; 268int row = g -> args [1 ]; 269int startcol = g -> args [2 ]; 270Integer endcol = startcol + g -> coloff ; 271Integer clearcol = endcol + g -> clear_width ; 272LineFlags lineflags = g -> wrap ?kLineFlagWrap :0 ; 273 274tui_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{ 281if (args .size < 1 || args .items [0 ].type != kObjectTypeString ) { 282ELOG ("Error handling UI event 'connect'" ); 283return ; 284 } 285 286String s = args .items [0 ].data .string ; 287char * server_addr = xmemdupz (s .data ,s .size ); 288multiqueue_put (main_loop .fast_events ,channel_connect_event ,server_addr ); 289// Set a dummy channel ID to prevent client exit when server detaches. 290ui_client_channel_id = UINT64_MAX ; 291} 292 293static void channel_connect_event (void ** argv ) 294{ 295char * server_addr = argv [0 ]; 296 297const char * err = "" ; 298bool is_tcp = socket_address_tcp_host_end (server_addr )!= NULL ; 299CallbackReader on_data = CALLBACK_READER_INIT ; 300uint64_t chan = channel_connect (is_tcp ,server_addr , true,on_data ,50 ,& err ); 301 302if (!strequal (err ,"" )) { 303ELOG ("Cannot connect to server %s: %s" ,server_addr ,err ); 304xfree (server_addr ); 305ui_client_exit_status = 1 ; 306os_exit (1 ); 307 } 308 309ui_client_channel_id = chan ; 310ui_client_attach (tui_width ,tui_height ,tui_term ,tui_rgb ); 311 312ILOG ("Connected to server %s on channel %" PRId64 ,server_addr ,chan ); 313xfree (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. 332api_free_array (restart_args ); 333restart_args = copy_array (args ,NULL ); 334restart_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. 340api_free_array (restart_args_after_crash_exit ); 341restart_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{ 347Array args = restart_args ; 348bool restart = false; 349if (!restart_pending ) { 350if (error_restart && ui_client_error_exit == -1 && restart_args_after_crash_exit .size > 0 ) { 351restart = true; 352args = restart_args_after_crash_exit ; 353 }else { 354return ; 355 } 356 } 357 358restart_pending = false; 359 360if (args .size < 1 || args .items [0 ].type != kObjectTypeString ) { 361ELOG ("Error handling ui event 'restart'" ); 362 gotocleanup ; 363 } 364 365uint64_t chan_id ; 366const char * first_arg = args .items [0 ].data .string .data ; 367if (restart ) { 368if (args .size < 2 || args .items [1 ].type != kObjectTypeArray ) { 369ELOG ("Error handling ui event 'restart'" ); 370 gotocleanup ; 371 } 372Array cmdargs = args .items [1 ].data .array ; 373char ** argv = xcalloc (cmdargs .size + 1 ,sizeof (char * )); 374for (size_t i = 0 ;i < cmdargs .size ;i ++ ) { 375if (cmdargs .items [i ].type == kObjectTypeString ) { 376argv [i ]= cmdargs .items [i ].data .string .data ; 377 } 378if (argv [i ]== NULL ) { 379argv [i ]= "" ; 380 } 381 } 382chan_id = ui_client_start_server (first_arg ,cmdargs .size ,argv ); 383xfree (argv ); 384ui_client_error_exit = -1 ; 385 }else { 386bool is_tcp = socket_address_tcp_host_end (first_arg )!= NULL ; 387const char * err = NULL ; 388chan_id = channel_connect (is_tcp ,first_arg , true,CALLBACK_READER_INIT ,50 ,& err ); 389if (err != NULL ) { 390ELOG ("cannot connect to server %s: %s" ,first_arg ,err ); 391 gotocleanup ; 392 } 393 } 394 395// Client-side server re-attach. 396ui_client_channel_id = chan_id ; 397ui_client_attach (tui_width ,tui_height ,tui_term ,tui_rgb ); 398 399ILOG ("restarted server address=%s id=%" PRId64 ,first_arg ,chan_id ); 400cleanup : 401api_free_array (restart_args ); 402restart_args = (Array )ARRAY_DICT_INIT ; 403api_free_array (restart_args_after_crash_exit ); 404restart_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{ 410if (args .size < 1 411|| args .items [0 ].type != kObjectTypeInteger ) { 412ELOG ("Error handling ui event 'error_exit'" ); 413return ; 414 } 415ui_client_error_exit = (int )args .items [0 ].data .integer ; 416} 417 418#ifdef EXITFREE 419void ui_client_free_all_mem (void ) 420{ 421tui_free_all_mem (tui ); 422xfree (grid_line_buf_char ); 423xfree (grid_line_buf_attr ); 424} 425#endif