blob: 18a0e619b16af2450478287cacc44f2dd746ef97 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
39 *
40 * TODO:
41 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
42 * Higashi, 2017 Sep 19)
43 * - Shift-Tab does not work.
44 * - click in Window toolbar of other window: save/restore Insert and Visual
45 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
46 * is disabled.
47 * - implement term_setsize()
48 * - MS-Windows GUI: still need to type a key after shell exits? #1924
49 * - add test for giving error for invalid 'termsize' value.
50 * - support minimal size when 'termsize' is "rows*cols".
51 * - support minimal size when 'termsize' is empty?
52 * - GUI: when using tabs, focus in terminal, click on tab does not work.
53 * - GUI: when 'confirm' is set and trying to exit Vim, dialog offers to save
54 * changes to "!shell".
55 * (justrajdeep, 2017 Aug 22)
56 * - For the GUI fill termios with default values, perhaps like pangoterm:
57 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
58 * - if the job in the terminal does not support the mouse, we can use the
59 * mouse in the Terminal window for copy/paste.
60 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
61 * conversions.
62 * - In the GUI use a terminal emulator for :!cmd. Make the height the same as
63 * the window and position it higher up when it gets filled, so it looks like
64 * the text scrolls up.
65 * - Copy text in the vterm to the Vim buffer once in a while, so that
66 * completion works.
67 * - add an optional limit for the scrollback size. When reaching it remove
68 * 10% at the start.
69 */
70
71#include "vim.h"
72
73#if defined(FEAT_TERMINAL) || defined(PROTO)
74
75#ifndef MIN
76# define MIN(x,y) ((x) < (y) ? (x) : (y))
77#endif
78#ifndef MAX
79# define MAX(x,y) ((x) > (y) ? (x) : (y))
80#endif
81
82#include "libvterm/include/vterm.h"
83
84/* This is VTermScreenCell without the characters, thus much smaller. */
85typedef struct {
86 VTermScreenCellAttrs attrs;
87 char width;
88 VTermColor fg, bg;
89} cellattr_T;
90
91typedef struct sb_line_S {
92 int sb_cols; /* can differ per line */
93 cellattr_T *sb_cells; /* allocated */
94 cellattr_T sb_fill_attr; /* for short line */
95} sb_line_T;
96
97/* typedef term_T in structs.h */
98struct terminal_S {
99 term_T *tl_next;
100
101 VTerm *tl_vterm;
102 job_T *tl_job;
103 buf_T *tl_buffer;
104
105 /* Set when setting the size of a vterm, reset after redrawing. */
106 int tl_vterm_size_changed;
107
108 /* used when tl_job is NULL and only a pty was created */
109 int tl_tty_fd;
110 char_u *tl_tty_in;
111 char_u *tl_tty_out;
112
113 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
114 int tl_channel_closed;
115 int tl_finish; /* 'c' for ++close, 'o' for ++open */
116 char_u *tl_opencmd;
117 char_u *tl_eof_chars;
118
119#ifdef WIN3264
120 void *tl_winpty_config;
121 void *tl_winpty;
122#endif
123
124 /* last known vterm size */
125 int tl_rows;
126 int tl_cols;
127 /* vterm size does not follow window size */
128 int tl_rows_fixed;
129 int tl_cols_fixed;
130
131 char_u *tl_title; /* NULL or allocated */
132 char_u *tl_status_text; /* NULL or allocated */
133
134 /* Range of screen rows to update. Zero based. */
135 int tl_dirty_row_start; /* -1 if nothing dirty */
136 int tl_dirty_row_end; /* row below last one to update */
137
138 garray_T tl_scrollback;
139 int tl_scrollback_scrolled;
140 cellattr_T tl_default_color;
141
142 VTermPos tl_cursor_pos;
143 int tl_cursor_visible;
144 int tl_cursor_blink;
145 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
146 char_u *tl_cursor_color; /* NULL or allocated */
147
148 int tl_using_altscreen;
149};
150
151#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
152#define TMODE_LOOP 2 /* CTRL-W N used */
153
154/*
155 * List of all active terminals.
156 */
157static term_T *first_term = NULL;
158
159/* Terminal active in terminal_loop(). */
160static term_T *in_terminal_loop = NULL;
161
162#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
163#define KEY_BUF_LEN 200
164
165/*
166 * Functions with separate implementation for MS-Windows and Unix-like systems.
167 */
168static int term_and_job_init(term_T *term, typval_T *argvar, jobopt_T *opt);
169static int create_pty_only(term_T *term, jobopt_T *opt);
170static void term_report_winsize(term_T *term, int rows, int cols);
171static void term_free_vterm(term_T *term);
172
173/* The characters that we know (or assume) that the terminal expects for the
174 * backspace and enter keys. */
175static int term_backspace_char = BS;
176static int term_enter_char = CAR;
177static int term_nl_does_cr = FALSE;
178
179
180/**************************************
181 * 1. Generic code for all systems.
182 */
183
184/*
185 * Determine the terminal size from 'termsize' and the current window.
186 * Assumes term->tl_rows and term->tl_cols are zero.
187 */
188 static void
189set_term_and_win_size(term_T *term)
190{
191 if (*curwin->w_p_tms != NUL)
192 {
193 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
194
195 term->tl_rows = atoi((char *)curwin->w_p_tms);
196 term->tl_cols = atoi((char *)p);
197 }
198 if (term->tl_rows == 0)
199 term->tl_rows = curwin->w_height;
200 else
201 {
202 win_setheight_win(term->tl_rows, curwin);
203 term->tl_rows_fixed = TRUE;
204 }
205 if (term->tl_cols == 0)
206 term->tl_cols = curwin->w_width;
207 else
208 {
209 win_setwidth_win(term->tl_cols, curwin);
210 term->tl_cols_fixed = TRUE;
211 }
212}
213
214/*
215 * Initialize job options for a terminal job.
216 * Caller may overrule some of them.
217 */
218 static void
219init_job_options(jobopt_T *opt)
220{
221 clear_job_options(opt);
222
223 opt->jo_mode = MODE_RAW;
224 opt->jo_out_mode = MODE_RAW;
225 opt->jo_err_mode = MODE_RAW;
226 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
227}
228
229/*
230 * Set job options mandatory for a terminal job.
231 */
232 static void
233setup_job_options(jobopt_T *opt, int rows, int cols)
234{
235 if (!(opt->jo_set & JO_OUT_IO))
236 {
237 /* Connect stdout to the terminal. */
238 opt->jo_io[PART_OUT] = JIO_BUFFER;
239 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
240 opt->jo_modifiable[PART_OUT] = 0;
241 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
242 }
243
244 if (!(opt->jo_set & JO_ERR_IO))
245 {
246 /* Connect stderr to the terminal. */
247 opt->jo_io[PART_ERR] = JIO_BUFFER;
248 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
249 opt->jo_modifiable[PART_ERR] = 0;
250 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
251 }
252
253 opt->jo_pty = TRUE;
254 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
255 opt->jo_term_rows = rows;
256 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
257 opt->jo_term_cols = cols;
258}
259
260/*
261 * Start a terminal window and return its buffer.
262 * Returns NULL when failed.
263 */
264 static buf_T *
265term_start(typval_T *argvar, jobopt_T *opt, int forceit)
266{
267 exarg_T split_ea;
268 win_T *old_curwin = curwin;
269 term_T *term;
270 buf_T *old_curbuf = NULL;
271 int res;
272 buf_T *newbuf;
273
274 if (check_restricted() || check_secure())
275 return NULL;
276
277 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
278 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
279 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
280 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
281 {
282 EMSG(_(e_invarg));
283 return NULL;
284 }
285
286 term = (term_T *)alloc_clear(sizeof(term_T));
287 if (term == NULL)
288 return NULL;
289 term->tl_dirty_row_end = MAX_ROW;
290 term->tl_cursor_visible = TRUE;
291 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
292 term->tl_finish = opt->jo_term_finish;
293 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
294
295 vim_memset(&split_ea, 0, sizeof(split_ea));
296 if (opt->jo_curwin)
297 {
298 /* Create a new buffer in the current window. */
299 if (!can_abandon(curbuf, forceit))
300 {
301 no_write_message();
302 vim_free(term);
303 return NULL;
304 }
305 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
306 ECMD_HIDE + (forceit ? ECMD_FORCEIT : 0), curwin) == FAIL)
307 {
308 vim_free(term);
309 return NULL;
310 }
311 }
312 else if (opt->jo_hidden)
313 {
314 buf_T *buf;
315
316 /* Create a new buffer without a window. Make it the current buffer for
317 * a moment to be able to do the initialisations. */
318 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
319 BLN_NEW | BLN_LISTED);
320 if (buf == NULL || ml_open(buf) == FAIL)
321 {
322 vim_free(term);
323 return NULL;
324 }
325 old_curbuf = curbuf;
326 --curbuf->b_nwindows;
327 curbuf = buf;
328 curwin->w_buffer = buf;
329 ++curbuf->b_nwindows;
330 }
331 else
332 {
333 /* Open a new window or tab. */
334 split_ea.cmdidx = CMD_new;
335 split_ea.cmd = (char_u *)"new";
336 split_ea.arg = (char_u *)"";
337 if (opt->jo_term_rows > 0 && !(cmdmod.split & WSP_VERT))
338 {
339 split_ea.line2 = opt->jo_term_rows;
340 split_ea.addr_count = 1;
341 }
342 if (opt->jo_term_cols > 0 && (cmdmod.split & WSP_VERT))
343 {
344 split_ea.line2 = opt->jo_term_cols;
345 split_ea.addr_count = 1;
346 }
347
348 ex_splitview(&split_ea);
349 if (curwin == old_curwin)
350 {
351 /* split failed */
352 vim_free(term);
353 return NULL;
354 }
355 }
356 term->tl_buffer = curbuf;
357 curbuf->b_term = term;
358
359 if (!opt->jo_hidden)
360 {
361 /* only one size was taken care of with :new, do the other one */
362 if (opt->jo_term_rows > 0 && (cmdmod.split & WSP_VERT))
363 win_setheight(opt->jo_term_rows);
364 if (opt->jo_term_cols > 0 && !(cmdmod.split & WSP_VERT))
365 win_setwidth(opt->jo_term_cols);
366 }
367
368 /* Link the new terminal in the list of active terminals. */
369 term->tl_next = first_term;
370 first_term = term;
371
372 if (opt->jo_term_name != NULL)
373 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
374 else
375 {
376 int i;
377 size_t len;
378 char_u *cmd, *p;
379
380 if (argvar->v_type == VAR_STRING)
381 {
382 cmd = argvar->vval.v_string;
383 if (cmd == NULL)
384 cmd = (char_u *)"";
385 else if (STRCMP(cmd, "NONE") == 0)
386 cmd = (char_u *)"pty";
387 }
388 else if (argvar->v_type != VAR_LIST
389 || argvar->vval.v_list == NULL
390 || argvar->vval.v_list->lv_len < 1
391 || (cmd = get_tv_string_chk(
392 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
393 cmd = (char_u*)"";
394
395 len = STRLEN(cmd) + 10;
396 p = alloc((int)len);
397
398 for (i = 0; p != NULL; ++i)
399 {
400 /* Prepend a ! to the command name to avoid the buffer name equals
401 * the executable, otherwise ":w!" would overwrite it. */
402 if (i == 0)
403 vim_snprintf((char *)p, len, "!%s", cmd);
404 else
405 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
406 if (buflist_findname(p) == NULL)
407 {
408 vim_free(curbuf->b_ffname);
409 curbuf->b_ffname = p;
410 break;
411 }
412 }
413 }
414 curbuf->b_fname = curbuf->b_ffname;
415
416 if (opt->jo_term_opencmd != NULL)
417 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
418
419 if (opt->jo_eof_chars != NULL)
420 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
421
422 set_string_option_direct((char_u *)"buftype", -1,
423 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
424
425 /* Mark the buffer as not modifiable. It can only be made modifiable after
426 * the job finished. */
427 curbuf->b_p_ma = FALSE;
428
429 set_term_and_win_size(term);
430 setup_job_options(opt, term->tl_rows, term->tl_cols);
431
432 /* System dependent: setup the vterm and maybe start the job in it. */
433 if (argvar->v_type == VAR_STRING
434 && argvar->vval.v_string != NULL
435 && STRCMP(argvar->vval.v_string, "NONE") == 0)
436 res = create_pty_only(term, opt);
437 else
438 res = term_and_job_init(term, argvar, opt);
439
440 newbuf = curbuf;
441 if (res == OK)
442 {
443 /* Get and remember the size we ended up with. Update the pty. */
444 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
445 term_report_winsize(term, term->tl_rows, term->tl_cols);
446
447 /* Make sure we don't get stuck on sending keys to the job, it leads to
448 * a deadlock if the job is waiting for Vim to read. */
449 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
450
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200451#ifdef FEAT_AUTOCMD
452 ++curbuf->b_locked;
453 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
454 --curbuf->b_locked;
455#endif
456
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457 if (old_curbuf != NULL)
458 {
459 --curbuf->b_nwindows;
460 curbuf = old_curbuf;
461 curwin->w_buffer = curbuf;
462 ++curbuf->b_nwindows;
463 }
464 }
465 else
466 {
467 buf_T *buf = curbuf;
468
469 free_terminal(curbuf);
470 if (old_curbuf != NULL)
471 {
472 --curbuf->b_nwindows;
473 curbuf = old_curbuf;
474 curwin->w_buffer = curbuf;
475 ++curbuf->b_nwindows;
476 }
477
478 /* Wiping out the buffer will also close the window and call
479 * free_terminal(). */
480 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
481 return NULL;
482 }
483 return newbuf;
484}
485
486/*
487 * ":terminal": open a terminal window and execute a job in it.
488 */
489 void
490ex_terminal(exarg_T *eap)
491{
492 typval_T argvar[2];
493 jobopt_T opt;
494 char_u *cmd;
495 char_u *tofree = NULL;
496
497 init_job_options(&opt);
498
499 cmd = eap->arg;
500 while (*cmd && *cmd == '+' && *(cmd + 1) == '+')
501 {
502 char_u *p, *ep;
503
504 cmd += 2;
505 p = skiptowhite(cmd);
506 ep = vim_strchr(cmd, '=');
507 if (ep != NULL && ep < p)
508 p = ep;
509
510 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
511 opt.jo_term_finish = 'c';
512 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
513 opt.jo_term_finish = 'o';
514 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
515 opt.jo_curwin = 1;
516 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
517 opt.jo_hidden = 1;
518 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
519 && ep != NULL && isdigit(ep[1]))
520 {
521 opt.jo_set2 |= JO2_TERM_ROWS;
522 opt.jo_term_rows = atoi((char *)ep + 1);
523 p = skiptowhite(cmd);
524 }
525 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
526 && ep != NULL && isdigit(ep[1]))
527 {
528 opt.jo_set2 |= JO2_TERM_COLS;
529 opt.jo_term_cols = atoi((char *)ep + 1);
530 p = skiptowhite(cmd);
531 }
532 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
533 && ep != NULL)
534 {
535 char_u *buf = NULL;
536 char_u *keys;
537
538 p = skiptowhite(cmd);
539 *p = NUL;
540 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
541 opt.jo_set2 |= JO2_EOF_CHARS;
542 opt.jo_eof_chars = vim_strsave(keys);
543 vim_free(buf);
544 *p = ' ';
545 }
546 else
547 {
548 if (*p)
549 *p = NUL;
550 EMSG2(_("E181: Invalid attribute: %s"), cmd);
551 return;
552 }
553 cmd = skipwhite(p);
554 }
555 if (*cmd == NUL)
556 /* Make a copy of 'shell', an autocommand may change the option. */
557 tofree = cmd = vim_strsave(p_sh);
558
559 if (eap->addr_count > 0)
560 {
561 /* Write lines from current buffer to the job. */
562 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
563 opt.jo_io[PART_IN] = JIO_BUFFER;
564 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
565 opt.jo_in_top = eap->line1;
566 opt.jo_in_bot = eap->line2;
567 }
568
569 argvar[0].v_type = VAR_STRING;
570 argvar[0].vval.v_string = cmd;
571 argvar[1].v_type = VAR_UNKNOWN;
572 term_start(argvar, &opt, eap->forceit);
573 vim_free(tofree);
574 vim_free(opt.jo_eof_chars);
575}
576
577/*
578 * Free the scrollback buffer for "term".
579 */
580 static void
581free_scrollback(term_T *term)
582{
583 int i;
584
585 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
586 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
587 ga_clear(&term->tl_scrollback);
588}
589
590/*
591 * Free a terminal and everything it refers to.
592 * Kills the job if there is one.
593 * Called when wiping out a buffer.
594 */
595 void
596free_terminal(buf_T *buf)
597{
598 term_T *term = buf->b_term;
599 term_T *tp;
600
601 if (term == NULL)
602 return;
603 if (first_term == term)
604 first_term = term->tl_next;
605 else
606 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
607 if (tp->tl_next == term)
608 {
609 tp->tl_next = term->tl_next;
610 break;
611 }
612
613 if (term->tl_job != NULL)
614 {
615 if (term->tl_job->jv_status != JOB_ENDED
616 && term->tl_job->jv_status != JOB_FINISHED
617 && term->tl_job->jv_status != JOB_FAILED)
618 job_stop(term->tl_job, NULL, "kill");
619 job_unref(term->tl_job);
620 }
621
622 free_scrollback(term);
623
624 term_free_vterm(term);
625 vim_free(term->tl_title);
626 vim_free(term->tl_status_text);
627 vim_free(term->tl_opencmd);
628 vim_free(term->tl_eof_chars);
629 vim_free(term->tl_cursor_color);
630 vim_free(term);
631 buf->b_term = NULL;
632 if (in_terminal_loop == term)
633 in_terminal_loop = NULL;
634}
635
636/*
637 * Write job output "msg[len]" to the vterm.
638 */
639 static void
640term_write_job_output(term_T *term, char_u *msg, size_t len)
641{
642 VTerm *vterm = term->tl_vterm;
643 char_u *p;
644 size_t done;
645 size_t len_now;
646
647 if (term_nl_does_cr)
648 vterm_input_write(vterm, (char *)msg, len);
649 else
650 /* need to convert NL to CR-NL */
651 for (done = 0; done < len; done += len_now)
652 {
653 for (p = msg + done; p < msg + len; )
654 {
655 if (*p == NL)
656 break;
657 p += utf_ptr2len_len(p, (int)(len - (p - msg)));
658 }
659 len_now = p - msg - done;
660 vterm_input_write(vterm, (char *)msg + done, len_now);
661 if (p < msg + len && *p == NL)
662 {
663 vterm_input_write(vterm, "\r\n", 2);
664 ++len_now;
665 }
666 }
667
668 /* this invokes the damage callbacks */
669 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
670}
671
672 static void
673update_cursor(term_T *term, int redraw)
674{
675 if (term->tl_normal_mode)
676 return;
677 setcursor();
678 if (redraw)
679 {
680 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
681 cursor_on();
682 out_flush();
683#ifdef FEAT_GUI
684 if (gui.in_use)
685 gui_update_cursor(FALSE, FALSE);
686#endif
687 }
688}
689
690/*
691 * Invoked when "msg" output from a job was received. Write it to the terminal
692 * of "buffer".
693 */
694 void
695write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
696{
697 size_t len = STRLEN(msg);
698 term_T *term = buffer->b_term;
699
700 if (term->tl_vterm == NULL)
701 {
702 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
703 return;
704 }
705 ch_log(channel, "writing %d bytes to terminal", (int)len);
706 term_write_job_output(term, msg, len);
707
708 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
709 * contents, thus no screen update is needed. */
710 if (!term->tl_normal_mode)
711 {
712 /* TODO: only update once in a while. */
713 ch_log(term->tl_job->jv_channel, "updating screen");
714 if (buffer == curbuf)
715 {
716 update_screen(0);
717 update_cursor(term, TRUE);
718 }
719 else
720 redraw_after_callback(TRUE);
721 }
722}
723
724/*
725 * Send a mouse position and click to the vterm
726 */
727 static int
728term_send_mouse(VTerm *vterm, int button, int pressed)
729{
730 VTermModifier mod = VTERM_MOD_NONE;
731
732 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200733 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734 vterm_mouse_button(vterm, button, pressed, mod);
735 return TRUE;
736}
737
738/*
739 * Convert typed key "c" into bytes to send to the job.
740 * Return the number of bytes in "buf".
741 */
742 static int
743term_convert_key(term_T *term, int c, char *buf)
744{
745 VTerm *vterm = term->tl_vterm;
746 VTermKey key = VTERM_KEY_NONE;
747 VTermModifier mod = VTERM_MOD_NONE;
748 int mouse = FALSE;
749
750 switch (c)
751 {
752 case CAR: c = term_enter_char; break;
753 /* don't use VTERM_KEY_BACKSPACE, it always
754 * becomes 0x7f DEL */
755 case K_BS: c = term_backspace_char; break;
756
757 case ESC: key = VTERM_KEY_ESCAPE; break;
758 case K_DEL: key = VTERM_KEY_DEL; break;
759 case K_DOWN: key = VTERM_KEY_DOWN; break;
760 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
761 key = VTERM_KEY_DOWN; break;
762 case K_END: key = VTERM_KEY_END; break;
763 case K_S_END: mod = VTERM_MOD_SHIFT;
764 key = VTERM_KEY_END; break;
765 case K_C_END: mod = VTERM_MOD_CTRL;
766 key = VTERM_KEY_END; break;
767 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
768 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
769 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
770 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
771 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
772 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
773 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
774 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
775 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
776 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
777 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
778 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
779 case K_HOME: key = VTERM_KEY_HOME; break;
780 case K_S_HOME: mod = VTERM_MOD_SHIFT;
781 key = VTERM_KEY_HOME; break;
782 case K_C_HOME: mod = VTERM_MOD_CTRL;
783 key = VTERM_KEY_HOME; break;
784 case K_INS: key = VTERM_KEY_INS; break;
785 case K_K0: key = VTERM_KEY_KP_0; break;
786 case K_K1: key = VTERM_KEY_KP_1; break;
787 case K_K2: key = VTERM_KEY_KP_2; break;
788 case K_K3: key = VTERM_KEY_KP_3; break;
789 case K_K4: key = VTERM_KEY_KP_4; break;
790 case K_K5: key = VTERM_KEY_KP_5; break;
791 case K_K6: key = VTERM_KEY_KP_6; break;
792 case K_K7: key = VTERM_KEY_KP_7; break;
793 case K_K8: key = VTERM_KEY_KP_8; break;
794 case K_K9: key = VTERM_KEY_KP_9; break;
795 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
796 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
797 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
798 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
799 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
800 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
801 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
802 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
803 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
804 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
805 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
806 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
807 case K_LEFT: key = VTERM_KEY_LEFT; break;
808 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
809 key = VTERM_KEY_LEFT; break;
810 case K_C_LEFT: mod = VTERM_MOD_CTRL;
811 key = VTERM_KEY_LEFT; break;
812 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
813 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
814 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
815 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
816 key = VTERM_KEY_RIGHT; break;
817 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
818 key = VTERM_KEY_RIGHT; break;
819 case K_UP: key = VTERM_KEY_UP; break;
820 case K_S_UP: mod = VTERM_MOD_SHIFT;
821 key = VTERM_KEY_UP; break;
822 case TAB: key = VTERM_KEY_TAB; break;
823
824 case K_MOUSEUP: mouse = term_send_mouse(vterm, 5, 1); break;
825 case K_MOUSEDOWN: mouse = term_send_mouse(vterm, 4, 1); break;
826 case K_MOUSELEFT: /* TODO */ return 0;
827 case K_MOUSERIGHT: /* TODO */ return 0;
828
829 case K_LEFTMOUSE:
830 case K_LEFTMOUSE_NM: mouse = term_send_mouse(vterm, 1, 1); break;
831 case K_LEFTDRAG: mouse = term_send_mouse(vterm, 1, 1); break;
832 case K_LEFTRELEASE:
833 case K_LEFTRELEASE_NM: mouse = term_send_mouse(vterm, 1, 0); break;
834 case K_MIDDLEMOUSE: mouse = term_send_mouse(vterm, 2, 1); break;
835 case K_MIDDLEDRAG: mouse = term_send_mouse(vterm, 2, 1); break;
836 case K_MIDDLERELEASE: mouse = term_send_mouse(vterm, 2, 0); break;
837 case K_RIGHTMOUSE: mouse = term_send_mouse(vterm, 3, 1); break;
838 case K_RIGHTDRAG: mouse = term_send_mouse(vterm, 3, 1); break;
839 case K_RIGHTRELEASE: mouse = term_send_mouse(vterm, 3, 0); break;
840 case K_X1MOUSE: /* TODO */ return 0;
841 case K_X1DRAG: /* TODO */ return 0;
842 case K_X1RELEASE: /* TODO */ return 0;
843 case K_X2MOUSE: /* TODO */ return 0;
844 case K_X2DRAG: /* TODO */ return 0;
845 case K_X2RELEASE: /* TODO */ return 0;
846
847 case K_IGNORE: return 0;
848 case K_NOP: return 0;
849 case K_UNDO: return 0;
850 case K_HELP: return 0;
851 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
852 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
853 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
854 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
855 case K_SELECT: return 0;
856#ifdef FEAT_GUI
857 case K_VER_SCROLLBAR: return 0;
858 case K_HOR_SCROLLBAR: return 0;
859#endif
860#ifdef FEAT_GUI_TABLINE
861 case K_TABLINE: return 0;
862 case K_TABMENU: return 0;
863#endif
864#ifdef FEAT_NETBEANS_INTG
865 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
866#endif
867#ifdef FEAT_DND
868 case K_DROP: return 0;
869#endif
870#ifdef FEAT_AUTOCMD
871 case K_CURSORHOLD: return 0;
872#endif
873 case K_PS: vterm_keyboard_start_paste(vterm); return 0;
874 case K_PE: vterm_keyboard_end_paste(vterm); return 0;
875 }
876
877 /*
878 * Convert special keys to vterm keys:
879 * - Write keys to vterm: vterm_keyboard_key()
880 * - Write output to channel.
881 * TODO: use mod_mask
882 */
883 if (key != VTERM_KEY_NONE)
884 /* Special key, let vterm convert it. */
885 vterm_keyboard_key(vterm, key, mod);
886 else if (!mouse)
887 /* Normal character, let vterm convert it. */
888 vterm_keyboard_unichar(vterm, c, mod);
889
890 /* Read back the converted escape sequence. */
891 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
892}
893
894/*
895 * Return TRUE if the job for "term" is still running.
896 */
897 int
898term_job_running(term_T *term)
899{
900 /* Also consider the job finished when the channel is closed, to avoid a
901 * race condition when updating the title. */
902 return term != NULL
903 && term->tl_job != NULL
904 && channel_is_open(term->tl_job->jv_channel)
905 && (term->tl_job->jv_status == JOB_STARTED
906 || term->tl_job->jv_channel->ch_keep_open);
907}
908
909/*
910 * Return TRUE if "term" has an active channel and used ":term NONE".
911 */
912 int
913term_none_open(term_T *term)
914{
915 /* Also consider the job finished when the channel is closed, to avoid a
916 * race condition when updating the title. */
917 return term != NULL
918 && term->tl_job != NULL
919 && channel_is_open(term->tl_job->jv_channel)
920 && term->tl_job->jv_channel->ch_keep_open;
921}
922
923/*
924 * Add the last line of the scrollback buffer to the buffer in the window.
925 */
926 static void
927add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
928{
929 buf_T *buf = term->tl_buffer;
930 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
931 linenr_T lnum = buf->b_ml.ml_line_count;
932
933#ifdef WIN3264
934 if (!enc_utf8 && enc_codepage > 0)
935 {
936 WCHAR *ret = NULL;
937 int length = 0;
938
939 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
940 &ret, &length);
941 if (ret != NULL)
942 {
943 WideCharToMultiByte_alloc(enc_codepage, 0,
944 ret, length, (char **)&text, &len, 0, 0);
945 vim_free(ret);
946 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
947 vim_free(text);
948 }
949 }
950 else
951#endif
952 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
953 if (empty)
954 {
955 /* Delete the empty line that was in the empty buffer. */
956 curbuf = buf;
957 ml_delete(1, FALSE);
958 curbuf = curwin->w_buffer;
959 }
960}
961
962 static void
963cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
964{
965 attr->width = cell->width;
966 attr->attrs = cell->attrs;
967 attr->fg = cell->fg;
968 attr->bg = cell->bg;
969}
970
971 static int
972equal_celattr(cellattr_T *a, cellattr_T *b)
973{
974 /* Comparing the colors should be sufficient. */
975 return a->fg.red == b->fg.red
976 && a->fg.green == b->fg.green
977 && a->fg.blue == b->fg.blue
978 && a->bg.red == b->bg.red
979 && a->bg.green == b->bg.green
980 && a->bg.blue == b->bg.blue;
981}
982
983
984/*
985 * Add the current lines of the terminal to scrollback and to the buffer.
986 * Called after the job has ended and when switching to Terminal-Normal mode.
987 */
988 static void
989move_terminal_to_buffer(term_T *term)
990{
991 win_T *wp;
992 int len;
993 int lines_skipped = 0;
994 VTermPos pos;
995 VTermScreenCell cell;
996 cellattr_T fill_attr, new_fill_attr;
997 cellattr_T *p;
998 VTermScreen *screen;
999
1000 if (term->tl_vterm == NULL)
1001 return;
1002 screen = vterm_obtain_screen(term->tl_vterm);
1003 fill_attr = new_fill_attr = term->tl_default_color;
1004
1005 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1006 {
1007 len = 0;
1008 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1009 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1010 && cell.chars[0] != NUL)
1011 {
1012 len = pos.col + 1;
1013 new_fill_attr = term->tl_default_color;
1014 }
1015 else
1016 /* Assume the last attr is the filler attr. */
1017 cell2cellattr(&cell, &new_fill_attr);
1018
1019 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1020 ++lines_skipped;
1021 else
1022 {
1023 while (lines_skipped > 0)
1024 {
1025 /* Line was skipped, add an empty line. */
1026 --lines_skipped;
1027 if (ga_grow(&term->tl_scrollback, 1) == OK)
1028 {
1029 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1030 + term->tl_scrollback.ga_len;
1031
1032 line->sb_cols = 0;
1033 line->sb_cells = NULL;
1034 line->sb_fill_attr = fill_attr;
1035 ++term->tl_scrollback.ga_len;
1036
1037 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1038 }
1039 }
1040
1041 if (len == 0)
1042 p = NULL;
1043 else
1044 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1045 if ((p != NULL || len == 0)
1046 && ga_grow(&term->tl_scrollback, 1) == OK)
1047 {
1048 garray_T ga;
1049 int width;
1050 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1051 + term->tl_scrollback.ga_len;
1052
1053 ga_init2(&ga, 1, 100);
1054 for (pos.col = 0; pos.col < len; pos.col += width)
1055 {
1056 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1057 {
1058 width = 1;
1059 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1060 if (ga_grow(&ga, 1) == OK)
1061 ga.ga_len += utf_char2bytes(' ',
1062 (char_u *)ga.ga_data + ga.ga_len);
1063 }
1064 else
1065 {
1066 width = cell.width;
1067
1068 cell2cellattr(&cell, &p[pos.col]);
1069
1070 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1071 {
1072 int i;
1073 int c;
1074
1075 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1076 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1077 (char_u *)ga.ga_data + ga.ga_len);
1078 }
1079 }
1080 }
1081 line->sb_cols = len;
1082 line->sb_cells = p;
1083 line->sb_fill_attr = new_fill_attr;
1084 fill_attr = new_fill_attr;
1085 ++term->tl_scrollback.ga_len;
1086
1087 if (ga_grow(&ga, 1) == FAIL)
1088 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1089 else
1090 {
1091 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1092 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1093 }
1094 ga_clear(&ga);
1095 }
1096 else
1097 vim_free(p);
1098 }
1099 }
1100
1101 /* Obtain the current background color. */
1102 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1103 &term->tl_default_color.fg, &term->tl_default_color.bg);
1104
1105 FOR_ALL_WINDOWS(wp)
1106 {
1107 if (wp->w_buffer == term->tl_buffer)
1108 {
1109 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1110 wp->w_cursor.col = 0;
1111 wp->w_valid = 0;
1112 if (wp->w_cursor.lnum >= wp->w_height)
1113 {
1114 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1115
1116 if (wp->w_topline < min_topline)
1117 wp->w_topline = min_topline;
1118 }
1119 redraw_win_later(wp, NOT_VALID);
1120 }
1121 }
1122}
1123
1124 static void
1125set_terminal_mode(term_T *term, int normal_mode)
1126{
1127 term->tl_normal_mode = normal_mode;
1128 vim_free(term->tl_status_text);
1129 term->tl_status_text = NULL;
1130 if (term->tl_buffer == curbuf)
1131 maketitle();
1132}
1133
1134/*
1135 * Called after the job if finished and Terminal mode is not active:
1136 * Move the vterm contents into the scrollback buffer and free the vterm.
1137 */
1138 static void
1139cleanup_vterm(term_T *term)
1140{
1141 if (term->tl_finish != 'c')
1142 move_terminal_to_buffer(term);
1143 term_free_vterm(term);
1144 set_terminal_mode(term, FALSE);
1145}
1146
1147/*
1148 * Switch from Terminal-Job mode to Terminal-Normal mode.
1149 * Suspends updating the terminal window.
1150 */
1151 static void
1152term_enter_normal_mode(void)
1153{
1154 term_T *term = curbuf->b_term;
1155
1156 /* Append the current terminal contents to the buffer. */
1157 move_terminal_to_buffer(term);
1158
1159 set_terminal_mode(term, TRUE);
1160
1161 /* Move the window cursor to the position of the cursor in the
1162 * terminal. */
1163 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1164 + term->tl_cursor_pos.row + 1;
1165 check_cursor();
1166 coladvance(term->tl_cursor_pos.col);
1167
1168 /* Display the same lines as in the terminal. */
1169 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1170}
1171
1172/*
1173 * Returns TRUE if the current window contains a terminal and we are in
1174 * Terminal-Normal mode.
1175 */
1176 int
1177term_in_normal_mode(void)
1178{
1179 term_T *term = curbuf->b_term;
1180
1181 return term != NULL && term->tl_normal_mode;
1182}
1183
1184/*
1185 * Switch from Terminal-Normal mode to Terminal-Job mode.
1186 * Restores updating the terminal window.
1187 */
1188 void
1189term_enter_job_mode()
1190{
1191 term_T *term = curbuf->b_term;
1192 sb_line_T *line;
1193 garray_T *gap;
1194
1195 /* Remove the terminal contents from the scrollback and the buffer. */
1196 gap = &term->tl_scrollback;
1197 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1198 && gap->ga_len > 0)
1199 {
1200 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1201 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1202 vim_free(line->sb_cells);
1203 --gap->ga_len;
1204 }
1205 check_cursor();
1206
1207 set_terminal_mode(term, FALSE);
1208
1209 if (term->tl_channel_closed)
1210 cleanup_vterm(term);
1211 redraw_buf_and_status_later(curbuf, NOT_VALID);
1212}
1213
1214/*
1215 * Get a key from the user without mapping.
1216 * Note: while waiting a terminal may be closed and freed if the channel is
1217 * closed and ++close was used.
1218 * Uses terminal mode mappings.
1219 */
1220 static int
1221term_vgetc()
1222{
1223 int c;
1224 int save_State = State;
1225
1226 State = TERMINAL;
1227 got_int = FALSE;
1228#ifdef WIN3264
1229 ctrl_break_was_pressed = FALSE;
1230#endif
1231 c = vgetc();
1232 got_int = FALSE;
1233 State = save_State;
1234 return c;
1235}
1236
1237/*
1238 * Get the part that is connected to the tty. Normally this is PART_IN, but
1239 * when writing buffer lines to the job it can be another. This makes it
1240 * possible to do "1,5term vim -".
1241 */
1242 static ch_part_T
1243get_tty_part(term_T *term)
1244{
1245#ifdef UNIX
1246 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1247 int i;
1248
1249 for (i = 0; i < 3; ++i)
1250 {
1251 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1252
1253 if (isatty(fd))
1254 return parts[i];
1255 }
1256#endif
1257 return PART_IN;
1258}
1259
1260/*
1261 * Send keys to terminal.
1262 * Return FAIL when the key needs to be handled in Normal mode.
1263 * Return OK when the key was dropped or sent to the terminal.
1264 */
1265 int
1266send_keys_to_term(term_T *term, int c, int typed)
1267{
1268 char msg[KEY_BUF_LEN];
1269 size_t len;
1270 static int mouse_was_outside = FALSE;
1271 int dragging_outside = FALSE;
1272
1273 /* Catch keys that need to be handled as in Normal mode. */
1274 switch (c)
1275 {
1276 case NUL:
1277 case K_ZERO:
1278 if (typed)
1279 stuffcharReadbuff(c);
1280 return FAIL;
1281
1282 case K_IGNORE:
1283 return FAIL;
1284
1285 case K_LEFTDRAG:
1286 case K_MIDDLEDRAG:
1287 case K_RIGHTDRAG:
1288 case K_X1DRAG:
1289 case K_X2DRAG:
1290 dragging_outside = mouse_was_outside;
1291 /* FALLTHROUGH */
1292 case K_LEFTMOUSE:
1293 case K_LEFTMOUSE_NM:
1294 case K_LEFTRELEASE:
1295 case K_LEFTRELEASE_NM:
1296 case K_MIDDLEMOUSE:
1297 case K_MIDDLERELEASE:
1298 case K_RIGHTMOUSE:
1299 case K_RIGHTRELEASE:
1300 case K_X1MOUSE:
1301 case K_X1RELEASE:
1302 case K_X2MOUSE:
1303 case K_X2RELEASE:
1304
1305 case K_MOUSEUP:
1306 case K_MOUSEDOWN:
1307 case K_MOUSELEFT:
1308 case K_MOUSERIGHT:
1309 if (mouse_row < W_WINROW(curwin)
1310 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001311 || mouse_col < curwin->w_wincol
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001312 || mouse_col >= W_ENDCOL(curwin)
1313 || dragging_outside)
1314 {
1315 /* click or scroll outside the current window */
1316 if (typed)
1317 {
1318 stuffcharReadbuff(c);
1319 mouse_was_outside = TRUE;
1320 }
1321 return FAIL;
1322 }
1323 }
1324 if (typed)
1325 mouse_was_outside = FALSE;
1326
1327 /* Convert the typed key to a sequence of bytes for the job. */
1328 len = term_convert_key(term, c, msg);
1329 if (len > 0)
1330 /* TODO: if FAIL is returned, stop? */
1331 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1332 (char_u *)msg, (int)len, NULL);
1333
1334 return OK;
1335}
1336
1337 static void
1338position_cursor(win_T *wp, VTermPos *pos)
1339{
1340 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1341 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1342 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1343}
1344
1345/*
1346 * Handle CTRL-W "": send register contents to the job.
1347 */
1348 static void
1349term_paste_register(int prev_c UNUSED)
1350{
1351 int c;
1352 list_T *l;
1353 listitem_T *item;
1354 long reglen = 0;
1355 int type;
1356
1357#ifdef FEAT_CMDL_INFO
1358 if (add_to_showcmd(prev_c))
1359 if (add_to_showcmd('"'))
1360 out_flush();
1361#endif
1362 c = term_vgetc();
1363#ifdef FEAT_CMDL_INFO
1364 clear_showcmd();
1365#endif
1366 if (!term_use_loop())
1367 /* job finished while waiting for a character */
1368 return;
1369
1370 /* CTRL-W "= prompt for expression to evaluate. */
1371 if (c == '=' && get_expr_register() != '=')
1372 return;
1373 if (!term_use_loop())
1374 /* job finished while waiting for a character */
1375 return;
1376
1377 l = (list_T *)get_reg_contents(c, GREG_LIST);
1378 if (l != NULL)
1379 {
1380 type = get_reg_type(c, &reglen);
1381 for (item = l->lv_first; item != NULL; item = item->li_next)
1382 {
1383 char_u *s = get_tv_string(&item->li_tv);
1384#ifdef WIN3264
1385 char_u *tmp = s;
1386
1387 if (!enc_utf8 && enc_codepage > 0)
1388 {
1389 WCHAR *ret = NULL;
1390 int length = 0;
1391
1392 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1393 (int)STRLEN(s), &ret, &length);
1394 if (ret != NULL)
1395 {
1396 WideCharToMultiByte_alloc(CP_UTF8, 0,
1397 ret, length, (char **)&s, &length, 0, 0);
1398 vim_free(ret);
1399 }
1400 }
1401#endif
1402 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1403 s, (int)STRLEN(s), NULL);
1404#ifdef WIN3264
1405 if (tmp != s)
1406 vim_free(s);
1407#endif
1408
1409 if (item->li_next != NULL || type == MLINE)
1410 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1411 (char_u *)"\r", 1, NULL);
1412 }
1413 list_free(l);
1414 }
1415}
1416
1417#if defined(FEAT_GUI) || defined(PROTO)
1418/*
1419 * Return TRUE when the cursor of the terminal should be displayed.
1420 */
1421 int
1422terminal_is_active()
1423{
1424 return in_terminal_loop != NULL;
1425}
1426
1427 cursorentry_T *
1428term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1429{
1430 term_T *term = in_terminal_loop;
1431 static cursorentry_T entry;
1432
1433 vim_memset(&entry, 0, sizeof(entry));
1434 entry.shape = entry.mshape =
1435 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1436 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1437 SHAPE_BLOCK;
1438 entry.percentage = 20;
1439 if (term->tl_cursor_blink)
1440 {
1441 entry.blinkwait = 700;
1442 entry.blinkon = 400;
1443 entry.blinkoff = 250;
1444 }
1445 *fg = gui.back_pixel;
1446 if (term->tl_cursor_color == NULL)
1447 *bg = gui.norm_pixel;
1448 else
1449 *bg = color_name2handle(term->tl_cursor_color);
1450 entry.name = "n";
1451 entry.used_for = SHAPE_CURSOR;
1452
1453 return &entry;
1454}
1455#endif
1456
1457static int did_change_cursor = FALSE;
1458
1459 static void
1460may_set_cursor_props(term_T *term)
1461{
1462#ifdef FEAT_GUI
1463 /* For the GUI the cursor properties are obtained with
1464 * term_get_cursor_shape(). */
1465 if (gui.in_use)
1466 return;
1467#endif
1468 if (in_terminal_loop == term)
1469 {
1470 did_change_cursor = TRUE;
1471 if (term->tl_cursor_color != NULL)
1472 term_cursor_color(term->tl_cursor_color);
1473 else
1474 term_cursor_color((char_u *)"");
1475 term_cursor_shape(term->tl_cursor_shape, term->tl_cursor_blink);
1476 }
1477}
1478
1479 static void
1480may_restore_cursor_props(void)
1481{
1482#ifdef FEAT_GUI
1483 if (gui.in_use)
1484 return;
1485#endif
1486 if (did_change_cursor)
1487 {
1488 did_change_cursor = FALSE;
1489 term_cursor_color((char_u *)"");
1490 /* this will restore the initial cursor style, if possible */
1491 ui_cursor_shape_forced(TRUE);
1492 }
1493}
1494
1495/*
1496 * Returns TRUE if the current window contains a terminal and we are sending
1497 * keys to the job.
1498 */
1499 int
1500term_use_loop(void)
1501{
1502 term_T *term = curbuf->b_term;
1503
1504 return term != NULL
1505 && !term->tl_normal_mode
1506 && term->tl_vterm != NULL
1507 && term_job_running(term);
1508}
1509
1510/*
1511 * Wait for input and send it to the job.
1512 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1513 * when there is no more typahead.
1514 * Return when the start of a CTRL-W command is typed or anything else that
1515 * should be handled as a Normal mode command.
1516 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1517 * the terminal was closed.
1518 */
1519 int
1520terminal_loop(int blocking)
1521{
1522 int c;
1523 int termkey = 0;
1524 int ret;
1525
1526 /* Remember the terminal we are sending keys to. However, the terminal
1527 * might be closed while waiting for a character, e.g. typing "exit" in a
1528 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1529 * stored reference. */
1530 in_terminal_loop = curbuf->b_term;
1531
1532 if (*curwin->w_p_tk != NUL)
1533 termkey = string_to_key(curwin->w_p_tk, TRUE);
1534 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1535 may_set_cursor_props(curbuf->b_term);
1536
1537#ifdef UNIX
1538 {
1539 int part = get_tty_part(curbuf->b_term);
1540 int fd = curbuf->b_term->tl_job->jv_channel->ch_part[part].ch_fd;
1541
1542 if (isatty(fd))
1543 {
1544 ttyinfo_T info;
1545
1546 /* Get the current backspace and enter characters of the pty. */
1547 if (get_tty_info(fd, &info) == OK)
1548 {
1549 term_backspace_char = info.backspace;
1550 term_enter_char = info.enter;
1551 term_nl_does_cr = info.nl_does_cr;
1552 }
1553 }
1554 }
1555#endif
1556
1557 while (blocking || vpeekc() != NUL)
1558 {
1559 /* TODO: skip screen update when handling a sequence of keys. */
1560 /* Repeat redrawing in case a message is received while redrawing. */
1561 while (must_redraw != 0)
1562 if (update_screen(0) == FAIL)
1563 break;
1564 update_cursor(curbuf->b_term, FALSE);
1565
1566 c = term_vgetc();
1567 if (!term_use_loop())
1568 /* job finished while waiting for a character */
1569 break;
1570 if (c == K_IGNORE)
1571 continue;
1572
1573#ifdef WIN3264
1574 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1575 * Use CTRL-BREAK to kill the job. */
1576 if (ctrl_break_was_pressed)
1577 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1578#endif
1579 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1580 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1581 {
1582 int prev_c = c;
1583
1584#ifdef FEAT_CMDL_INFO
1585 if (add_to_showcmd(c))
1586 out_flush();
1587#endif
1588 c = term_vgetc();
1589#ifdef FEAT_CMDL_INFO
1590 clear_showcmd();
1591#endif
1592 if (!term_use_loop())
1593 /* job finished while waiting for a character */
1594 break;
1595
1596 if (prev_c == Ctrl_BSL)
1597 {
1598 if (c == Ctrl_N)
1599 {
1600 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1601 term_enter_normal_mode();
1602 ret = FAIL;
1603 goto theend;
1604 }
1605 /* Send both keys to the terminal. */
1606 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1607 }
1608 else if (c == Ctrl_C)
1609 {
1610 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1611 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1612 }
1613 else if (termkey == 0 && c == '.')
1614 {
1615 /* "CTRL-W .": send CTRL-W to the job */
1616 c = Ctrl_W;
1617 }
1618 else if (c == 'N')
1619 {
1620 /* CTRL-W N : go to Terminal-Normal mode. */
1621 term_enter_normal_mode();
1622 ret = FAIL;
1623 goto theend;
1624 }
1625 else if (c == '"')
1626 {
1627 term_paste_register(prev_c);
1628 continue;
1629 }
1630 else if (termkey == 0 || c != termkey)
1631 {
1632 stuffcharReadbuff(Ctrl_W);
1633 stuffcharReadbuff(c);
1634 ret = OK;
1635 goto theend;
1636 }
1637 }
1638# ifdef WIN3264
1639 if (!enc_utf8 && has_mbyte && c >= 0x80)
1640 {
1641 WCHAR wc;
1642 char_u mb[3];
1643
1644 mb[0] = (unsigned)c >> 8;
1645 mb[1] = c;
1646 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1647 c = wc;
1648 }
1649# endif
1650 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1651 {
1652 ret = OK;
1653 goto theend;
1654 }
1655 }
1656 ret = FAIL;
1657
1658theend:
1659 in_terminal_loop = NULL;
1660 may_restore_cursor_props();
1661 return ret;
1662}
1663
1664/*
1665 * Called when a job has finished.
1666 * This updates the title and status, but does not close the vterm, because
1667 * there might still be pending output in the channel.
1668 */
1669 void
1670term_job_ended(job_T *job)
1671{
1672 term_T *term;
1673 int did_one = FALSE;
1674
1675 for (term = first_term; term != NULL; term = term->tl_next)
1676 if (term->tl_job == job)
1677 {
1678 vim_free(term->tl_title);
1679 term->tl_title = NULL;
1680 vim_free(term->tl_status_text);
1681 term->tl_status_text = NULL;
1682 redraw_buf_and_status_later(term->tl_buffer, VALID);
1683 did_one = TRUE;
1684 }
1685 if (did_one)
1686 redraw_statuslines();
1687 if (curbuf->b_term != NULL)
1688 {
1689 if (curbuf->b_term->tl_job == job)
1690 maketitle();
1691 update_cursor(curbuf->b_term, TRUE);
1692 }
1693}
1694
1695 static void
1696may_toggle_cursor(term_T *term)
1697{
1698 if (in_terminal_loop == term)
1699 {
1700 if (term->tl_cursor_visible)
1701 cursor_on();
1702 else
1703 cursor_off();
1704 }
1705}
1706
1707/*
1708 * Reverse engineer the RGB value into a cterm color index.
1709 * First color is 1. Return 0 if no match found.
1710 */
1711 static int
1712color2index(VTermColor *color, int fg, int *boldp)
1713{
1714 int red = color->red;
1715 int blue = color->blue;
1716 int green = color->green;
1717
1718 /* The argument for lookup_color() is for the color_names[] table. */
1719 if (red == 0)
1720 {
1721 if (green == 0)
1722 {
1723 if (blue == 0)
1724 return lookup_color(0, fg, boldp) + 1; /* black */
1725 if (blue == 224)
1726 return lookup_color(1, fg, boldp) + 1; /* dark blue */
1727 }
1728 else if (green == 224)
1729 {
1730 if (blue == 0)
1731 return lookup_color(2, fg, boldp) + 1; /* dark green */
1732 if (blue == 224)
1733 return lookup_color(3, fg, boldp) + 1; /* dark cyan */
1734 }
1735 }
1736 else if (red == 224)
1737 {
1738 if (green == 0)
1739 {
1740 if (blue == 0)
1741 return lookup_color(4, fg, boldp) + 1; /* dark red */
1742 if (blue == 224)
1743 return lookup_color(5, fg, boldp) + 1; /* dark magenta */
1744 }
1745 else if (green == 224)
1746 {
1747 if (blue == 0)
1748 return lookup_color(6, fg, boldp) + 1; /* dark yellow / brown */
1749 if (blue == 224)
1750 return lookup_color(8, fg, boldp) + 1; /* white / light grey */
1751 }
1752 }
1753 else if (red == 128)
1754 {
1755 if (green == 128 && blue == 128)
1756 return lookup_color(12, fg, boldp) + 1; /* dark grey */
1757 }
1758 else if (red == 255)
1759 {
1760 if (green == 64)
1761 {
1762 if (blue == 64)
1763 return lookup_color(20, fg, boldp) + 1; /* light red */
1764 if (blue == 255)
1765 return lookup_color(22, fg, boldp) + 1; /* light magenta */
1766 }
1767 else if (green == 255)
1768 {
1769 if (blue == 64)
1770 return lookup_color(24, fg, boldp) + 1; /* yellow */
1771 if (blue == 255)
1772 return lookup_color(26, fg, boldp) + 1; /* white */
1773 }
1774 }
1775 else if (red == 64)
1776 {
1777 if (green == 64)
1778 {
1779 if (blue == 255)
1780 return lookup_color(14, fg, boldp) + 1; /* light blue */
1781 }
1782 else if (green == 255)
1783 {
1784 if (blue == 64)
1785 return lookup_color(16, fg, boldp) + 1; /* light green */
1786 if (blue == 255)
1787 return lookup_color(18, fg, boldp) + 1; /* light cyan */
1788 }
1789 }
1790 if (t_colors >= 256)
1791 {
1792 if (red == blue && red == green)
1793 {
1794 /* 24-color greyscale */
1795 static int cutoff[23] = {
1796 0x05, 0x10, 0x1B, 0x26, 0x31, 0x3C, 0x47, 0x52,
1797 0x5D, 0x68, 0x73, 0x7F, 0x8A, 0x95, 0xA0, 0xAB,
1798 0xB6, 0xC1, 0xCC, 0xD7, 0xE2, 0xED, 0xF9};
1799 int i;
1800
1801 for (i = 0; i < 23; ++i)
1802 if (red < cutoff[i])
1803 return i + 233;
1804 return 256;
1805 }
1806
1807 /* 216-color cube */
1808 return 17 + ((red + 25) / 0x33) * 36
1809 + ((green + 25) / 0x33) * 6
1810 + (blue + 25) / 0x33;
1811 }
1812 return 0;
1813}
1814
1815/*
1816 * Convert the attributes of a vterm cell into an attribute index.
1817 */
1818 static int
1819cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
1820{
1821 int attr = 0;
1822
1823 if (cellattrs.bold)
1824 attr |= HL_BOLD;
1825 if (cellattrs.underline)
1826 attr |= HL_UNDERLINE;
1827 if (cellattrs.italic)
1828 attr |= HL_ITALIC;
1829 if (cellattrs.strike)
1830 attr |= HL_STRIKETHROUGH;
1831 if (cellattrs.reverse)
1832 attr |= HL_INVERSE;
1833
1834#ifdef FEAT_GUI
1835 if (gui.in_use)
1836 {
1837 guicolor_T fg, bg;
1838
1839 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
1840 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
1841 return get_gui_attr_idx(attr, fg, bg);
1842 }
1843 else
1844#endif
1845#ifdef FEAT_TERMGUICOLORS
1846 if (p_tgc)
1847 {
1848 guicolor_T fg, bg;
1849
1850 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
1851 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
1852
1853 return get_tgc_attr_idx(attr, fg, bg);
1854 }
1855 else
1856#endif
1857 {
1858 int bold = MAYBE;
1859 int fg = color2index(&cellfg, TRUE, &bold);
1860 int bg = color2index(&cellbg, FALSE, &bold);
1861
1862 /* with 8 colors set the bold attribute to get a bright foreground */
1863 if (bold == TRUE)
1864 attr |= HL_BOLD;
1865 return get_cterm_attr_idx(attr, fg, bg);
1866 }
1867 return 0;
1868}
1869
1870 static int
1871handle_damage(VTermRect rect, void *user)
1872{
1873 term_T *term = (term_T *)user;
1874
1875 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
1876 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
1877 redraw_buf_later(term->tl_buffer, NOT_VALID);
1878 return 1;
1879}
1880
1881 static int
1882handle_moverect(VTermRect dest, VTermRect src, void *user)
1883{
1884 term_T *term = (term_T *)user;
1885
1886 /* Scrolling up is done much more efficiently by deleting lines instead of
1887 * redrawing the text. */
1888 if (dest.start_col == src.start_col
1889 && dest.end_col == src.end_col
1890 && dest.start_row < src.start_row)
1891 {
1892 win_T *wp;
1893 VTermColor fg, bg;
1894 VTermScreenCellAttrs attr;
1895 int clear_attr;
1896
1897 /* Set the color to clear lines with. */
1898 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1899 &fg, &bg);
1900 vim_memset(&attr, 0, sizeof(attr));
1901 clear_attr = cell2attr(attr, fg, bg);
1902
1903 FOR_ALL_WINDOWS(wp)
1904 {
1905 if (wp->w_buffer == term->tl_buffer)
1906 win_del_lines(wp, dest.start_row,
1907 src.start_row - dest.start_row, FALSE, FALSE,
1908 clear_attr);
1909 }
1910 }
1911 redraw_buf_later(term->tl_buffer, NOT_VALID);
1912 return 1;
1913}
1914
1915 static int
1916handle_movecursor(
1917 VTermPos pos,
1918 VTermPos oldpos UNUSED,
1919 int visible,
1920 void *user)
1921{
1922 term_T *term = (term_T *)user;
1923 win_T *wp;
1924
1925 term->tl_cursor_pos = pos;
1926 term->tl_cursor_visible = visible;
1927
1928 FOR_ALL_WINDOWS(wp)
1929 {
1930 if (wp->w_buffer == term->tl_buffer)
1931 position_cursor(wp, &pos);
1932 }
1933 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
1934 {
1935 may_toggle_cursor(term);
1936 update_cursor(term, term->tl_cursor_visible);
1937 }
1938
1939 return 1;
1940}
1941
1942 static int
1943handle_settermprop(
1944 VTermProp prop,
1945 VTermValue *value,
1946 void *user)
1947{
1948 term_T *term = (term_T *)user;
1949
1950 switch (prop)
1951 {
1952 case VTERM_PROP_TITLE:
1953 vim_free(term->tl_title);
1954 /* a blank title isn't useful, make it empty, so that "running" is
1955 * displayed */
1956 if (*skipwhite((char_u *)value->string) == NUL)
1957 term->tl_title = NULL;
1958#ifdef WIN3264
1959 else if (!enc_utf8 && enc_codepage > 0)
1960 {
1961 WCHAR *ret = NULL;
1962 int length = 0;
1963
1964 MultiByteToWideChar_alloc(CP_UTF8, 0,
1965 (char*)value->string, (int)STRLEN(value->string),
1966 &ret, &length);
1967 if (ret != NULL)
1968 {
1969 WideCharToMultiByte_alloc(enc_codepage, 0,
1970 ret, length, (char**)&term->tl_title,
1971 &length, 0, 0);
1972 vim_free(ret);
1973 }
1974 }
1975#endif
1976 else
1977 term->tl_title = vim_strsave((char_u *)value->string);
1978 vim_free(term->tl_status_text);
1979 term->tl_status_text = NULL;
1980 if (term == curbuf->b_term)
1981 maketitle();
1982 break;
1983
1984 case VTERM_PROP_CURSORVISIBLE:
1985 term->tl_cursor_visible = value->boolean;
1986 may_toggle_cursor(term);
1987 out_flush();
1988 break;
1989
1990 case VTERM_PROP_CURSORBLINK:
1991 term->tl_cursor_blink = value->boolean;
1992 may_set_cursor_props(term);
1993 break;
1994
1995 case VTERM_PROP_CURSORSHAPE:
1996 term->tl_cursor_shape = value->number;
1997 may_set_cursor_props(term);
1998 break;
1999
2000 case VTERM_PROP_CURSORCOLOR:
2001 vim_free(term->tl_cursor_color);
2002 if (*value->string == NUL)
2003 term->tl_cursor_color = NULL;
2004 else
2005 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2006 may_set_cursor_props(term);
2007 break;
2008
2009 case VTERM_PROP_ALTSCREEN:
2010 /* TODO: do anything else? */
2011 term->tl_using_altscreen = value->boolean;
2012 break;
2013
2014 default:
2015 break;
2016 }
2017 /* Always return 1, otherwise vterm doesn't store the value internally. */
2018 return 1;
2019}
2020
2021/*
2022 * The job running in the terminal resized the terminal.
2023 */
2024 static int
2025handle_resize(int rows, int cols, void *user)
2026{
2027 term_T *term = (term_T *)user;
2028 win_T *wp;
2029
2030 term->tl_rows = rows;
2031 term->tl_cols = cols;
2032 if (term->tl_vterm_size_changed)
2033 /* Size was set by vterm_set_size(), don't set the window size. */
2034 term->tl_vterm_size_changed = FALSE;
2035 else
2036 {
2037 FOR_ALL_WINDOWS(wp)
2038 {
2039 if (wp->w_buffer == term->tl_buffer)
2040 {
2041 win_setheight_win(rows, wp);
2042 win_setwidth_win(cols, wp);
2043 }
2044 }
2045 redraw_buf_later(term->tl_buffer, NOT_VALID);
2046 }
2047 return 1;
2048}
2049
2050/*
2051 * Handle a line that is pushed off the top of the screen.
2052 */
2053 static int
2054handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2055{
2056 term_T *term = (term_T *)user;
2057
2058 /* TODO: Limit the number of lines that are stored. */
2059 if (ga_grow(&term->tl_scrollback, 1) == OK)
2060 {
2061 cellattr_T *p = NULL;
2062 int len = 0;
2063 int i;
2064 int c;
2065 int col;
2066 sb_line_T *line;
2067 garray_T ga;
2068 cellattr_T fill_attr = term->tl_default_color;
2069
2070 /* do not store empty cells at the end */
2071 for (i = 0; i < cols; ++i)
2072 if (cells[i].chars[0] != 0)
2073 len = i + 1;
2074 else
2075 cell2cellattr(&cells[i], &fill_attr);
2076
2077 ga_init2(&ga, 1, 100);
2078 if (len > 0)
2079 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2080 if (p != NULL)
2081 {
2082 for (col = 0; col < len; col += cells[col].width)
2083 {
2084 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2085 {
2086 ga.ga_len = 0;
2087 break;
2088 }
2089 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2090 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2091 (char_u *)ga.ga_data + ga.ga_len);
2092 cell2cellattr(&cells[col], &p[col]);
2093 }
2094 }
2095 if (ga_grow(&ga, 1) == FAIL)
2096 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2097 else
2098 {
2099 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2100 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2101 }
2102 ga_clear(&ga);
2103
2104 line = (sb_line_T *)term->tl_scrollback.ga_data
2105 + term->tl_scrollback.ga_len;
2106 line->sb_cols = len;
2107 line->sb_cells = p;
2108 line->sb_fill_attr = fill_attr;
2109 ++term->tl_scrollback.ga_len;
2110 ++term->tl_scrollback_scrolled;
2111 }
2112 return 0; /* ignored */
2113}
2114
2115static VTermScreenCallbacks screen_callbacks = {
2116 handle_damage, /* damage */
2117 handle_moverect, /* moverect */
2118 handle_movecursor, /* movecursor */
2119 handle_settermprop, /* settermprop */
2120 NULL, /* bell */
2121 handle_resize, /* resize */
2122 handle_pushline, /* sb_pushline */
2123 NULL /* sb_popline */
2124};
2125
2126/*
2127 * Called when a channel has been closed.
2128 * If this was a channel for a terminal window then finish it up.
2129 */
2130 void
2131term_channel_closed(channel_T *ch)
2132{
2133 term_T *term;
2134 int did_one = FALSE;
2135
2136 for (term = first_term; term != NULL; term = term->tl_next)
2137 if (term->tl_job == ch->ch_job)
2138 {
2139 term->tl_channel_closed = TRUE;
2140 did_one = TRUE;
2141
2142 vim_free(term->tl_title);
2143 term->tl_title = NULL;
2144 vim_free(term->tl_status_text);
2145 term->tl_status_text = NULL;
2146
2147 /* Unless in Terminal-Normal mode: clear the vterm. */
2148 if (!term->tl_normal_mode)
2149 {
2150 int fnum = term->tl_buffer->b_fnum;
2151
2152 cleanup_vterm(term);
2153
2154 if (term->tl_finish == 'c')
2155 {
2156 /* ++close or term_finish == "close" */
2157 ch_log(NULL, "terminal job finished, closing window");
2158 curbuf = term->tl_buffer;
2159 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
2160 break;
2161 }
2162 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2163 {
2164 char buf[50];
2165
2166 /* TODO: use term_opencmd */
2167 ch_log(NULL, "terminal job finished, opening window");
2168 vim_snprintf(buf, sizeof(buf),
2169 term->tl_opencmd == NULL
2170 ? "botright sbuf %d"
2171 : (char *)term->tl_opencmd, fnum);
2172 do_cmdline_cmd((char_u *)buf);
2173 }
2174 else
2175 ch_log(NULL, "terminal job finished");
2176 }
2177
2178 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2179 }
2180 if (did_one)
2181 {
2182 redraw_statuslines();
2183
2184 /* Need to break out of vgetc(). */
2185 ins_char_typebuf(K_IGNORE);
2186 typebuf_was_filled = TRUE;
2187
2188 term = curbuf->b_term;
2189 if (term != NULL)
2190 {
2191 if (term->tl_job == ch->ch_job)
2192 maketitle();
2193 update_cursor(term, term->tl_cursor_visible);
2194 }
2195 }
2196}
2197
2198/*
2199 * Called to update a window that contains an active terminal.
2200 * Returns FAIL when there is no terminal running in this window or in
2201 * Terminal-Normal mode.
2202 */
2203 int
2204term_update_window(win_T *wp)
2205{
2206 term_T *term = wp->w_buffer->b_term;
2207 VTerm *vterm;
2208 VTermScreen *screen;
2209 VTermState *state;
2210 VTermPos pos;
2211
2212 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2213 return FAIL;
2214
2215 vterm = term->tl_vterm;
2216 screen = vterm_obtain_screen(vterm);
2217 state = vterm_obtain_state(vterm);
2218
2219 /*
2220 * If the window was resized a redraw will be triggered and we get here.
2221 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2222 */
2223 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2224 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2225 {
2226 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2227 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2228 win_T *twp;
2229
2230 FOR_ALL_WINDOWS(twp)
2231 {
2232 /* When more than one window shows the same terminal, use the
2233 * smallest size. */
2234 if (twp->w_buffer == term->tl_buffer)
2235 {
2236 if (!term->tl_rows_fixed && rows > twp->w_height)
2237 rows = twp->w_height;
2238 if (!term->tl_cols_fixed && cols > twp->w_width)
2239 cols = twp->w_width;
2240 }
2241 }
2242
2243 term->tl_vterm_size_changed = TRUE;
2244 vterm_set_size(vterm, rows, cols);
2245 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2246 rows);
2247 term_report_winsize(term, rows, cols);
2248 }
2249
2250 /* The cursor may have been moved when resizing. */
2251 vterm_state_get_cursorpos(state, &pos);
2252 position_cursor(wp, &pos);
2253
2254 /* TODO: Only redraw what changed. */
2255 for (pos.row = 0; pos.row < wp->w_height; ++pos.row)
2256 {
2257 int off = screen_get_current_line_off();
2258 int max_col = MIN(wp->w_width, term->tl_cols);
2259
2260 if (pos.row < term->tl_rows)
2261 {
2262 for (pos.col = 0; pos.col < max_col; )
2263 {
2264 VTermScreenCell cell;
2265 int c;
2266
2267 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2268 vim_memset(&cell, 0, sizeof(cell));
2269
2270 /* TODO: composing chars */
2271 c = cell.chars[0];
2272 if (c == NUL)
2273 {
2274 ScreenLines[off] = ' ';
2275 if (enc_utf8)
2276 ScreenLinesUC[off] = NUL;
2277 }
2278 else
2279 {
2280 if (enc_utf8)
2281 {
2282 if (c >= 0x80)
2283 {
2284 ScreenLines[off] = ' ';
2285 ScreenLinesUC[off] = c;
2286 }
2287 else
2288 {
2289 ScreenLines[off] = c;
2290 ScreenLinesUC[off] = NUL;
2291 }
2292 }
2293#ifdef WIN3264
2294 else if (has_mbyte && c >= 0x80)
2295 {
2296 char_u mb[MB_MAXBYTES+1];
2297 WCHAR wc = c;
2298
2299 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2300 (char*)mb, 2, 0, 0) > 1)
2301 {
2302 ScreenLines[off] = mb[0];
2303 ScreenLines[off + 1] = mb[1];
2304 cell.width = mb_ptr2cells(mb);
2305 }
2306 else
2307 ScreenLines[off] = c;
2308 }
2309#endif
2310 else
2311 ScreenLines[off] = c;
2312 }
2313 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2314
2315 ++pos.col;
2316 ++off;
2317 if (cell.width == 2)
2318 {
2319 if (enc_utf8)
2320 ScreenLinesUC[off] = NUL;
2321
2322 /* don't set the second byte to NUL for a DBCS encoding, it
2323 * has been set above */
2324 if (enc_utf8 || !has_mbyte)
2325 ScreenLines[off] = NUL;
2326
2327 ++pos.col;
2328 ++off;
2329 }
2330 }
2331 }
2332 else
2333 pos.col = 0;
2334
2335 screen_line(wp->w_winrow + pos.row, wp->w_wincol,
2336 pos.col, wp->w_width, FALSE);
2337 }
2338
2339 return OK;
2340}
2341
2342/*
2343 * Return TRUE if "wp" is a terminal window where the job has finished.
2344 */
2345 int
2346term_is_finished(buf_T *buf)
2347{
2348 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2349}
2350
2351/*
2352 * Return TRUE if "wp" is a terminal window where the job has finished or we
2353 * are in Terminal-Normal mode, thus we show the buffer contents.
2354 */
2355 int
2356term_show_buffer(buf_T *buf)
2357{
2358 term_T *term = buf->b_term;
2359
2360 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2361}
2362
2363/*
2364 * The current buffer is going to be changed. If there is terminal
2365 * highlighting remove it now.
2366 */
2367 void
2368term_change_in_curbuf(void)
2369{
2370 term_T *term = curbuf->b_term;
2371
2372 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2373 {
2374 free_scrollback(term);
2375 redraw_buf_later(term->tl_buffer, NOT_VALID);
2376
2377 /* The buffer is now like a normal buffer, it cannot be easily
2378 * abandoned when changed. */
2379 set_string_option_direct((char_u *)"buftype", -1,
2380 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2381 }
2382}
2383
2384/*
2385 * Get the screen attribute for a position in the buffer.
2386 * Use a negative "col" to get the filler background color.
2387 */
2388 int
2389term_get_attr(buf_T *buf, linenr_T lnum, int col)
2390{
2391 term_T *term = buf->b_term;
2392 sb_line_T *line;
2393 cellattr_T *cellattr;
2394
2395 if (lnum > term->tl_scrollback.ga_len)
2396 cellattr = &term->tl_default_color;
2397 else
2398 {
2399 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2400 if (col < 0 || col >= line->sb_cols)
2401 cellattr = &line->sb_fill_attr;
2402 else
2403 cellattr = line->sb_cells + col;
2404 }
2405 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2406}
2407
2408static VTermColor ansi_table[16] = {
2409 { 0, 0, 0}, /* black */
2410 {224, 0, 0}, /* dark red */
2411 { 0, 224, 0}, /* dark green */
2412 {224, 224, 0}, /* dark yellow / brown */
2413 { 0, 0, 224}, /* dark blue */
2414 {224, 0, 224}, /* dark magenta */
2415 { 0, 224, 224}, /* dark cyan */
2416 {224, 224, 224}, /* light grey */
2417
2418 {128, 128, 128}, /* dark grey */
2419 {255, 64, 64}, /* light red */
2420 { 64, 255, 64}, /* light green */
2421 {255, 255, 64}, /* yellow */
2422 { 64, 64, 255}, /* light blue */
2423 {255, 64, 255}, /* light magenta */
2424 { 64, 255, 255}, /* light cyan */
2425 {255, 255, 255}, /* white */
2426};
2427
2428static int cube_value[] = {
2429 0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF,
2430};
2431
2432static int grey_ramp[] = {
2433 0x00, 0x0B, 0x16, 0x21, 0x2C, 0x37, 0x42, 0x4D, 0x58, 0x63, 0x6E, 0x79,
2434 0x85, 0x90, 0x9B, 0xA6, 0xB1, 0xBC, 0xC7, 0xD2, 0xDD, 0xE8, 0xF3, 0xFF,
2435};
2436
2437/*
2438 * Convert a cterm color number 0 - 255 to RGB.
2439 */
2440 static void
2441cterm_color2rgb(int nr, VTermColor *rgb)
2442{
2443 int idx;
2444
2445 if (nr < 16)
2446 {
2447 *rgb = ansi_table[nr];
2448 }
2449 else if (nr < 232)
2450 {
2451 /* 216 color cube */
2452 idx = nr - 16;
2453 rgb->blue = cube_value[idx % 6];
2454 rgb->green = cube_value[idx / 6 % 6];
2455 rgb->red = cube_value[idx / 36 % 6];
2456 }
2457 else if (nr < 256)
2458 {
2459 /* 24 grey scale ramp */
2460 idx = nr - 232;
2461 rgb->blue = grey_ramp[idx];
2462 rgb->green = grey_ramp[idx];
2463 rgb->red = grey_ramp[idx];
2464 }
2465}
2466
2467/*
2468 * Create a new vterm and initialize it.
2469 */
2470 static void
2471create_vterm(term_T *term, int rows, int cols)
2472{
2473 VTerm *vterm;
2474 VTermScreen *screen;
2475 VTermValue value;
2476 VTermColor *fg, *bg;
2477 int fgval, bgval;
2478 int id;
2479
2480 vterm = vterm_new(rows, cols);
2481 term->tl_vterm = vterm;
2482 screen = vterm_obtain_screen(vterm);
2483 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2484 /* TODO: depends on 'encoding'. */
2485 vterm_set_utf8(vterm, 1);
2486
2487 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2488 term->tl_default_color.width = 1;
2489 fg = &term->tl_default_color.fg;
2490 bg = &term->tl_default_color.bg;
2491
2492 /* Vterm uses a default black background. Set it to white when
2493 * 'background' is "light". */
2494 if (*p_bg == 'l')
2495 {
2496 fgval = 0;
2497 bgval = 255;
2498 }
2499 else
2500 {
2501 fgval = 255;
2502 bgval = 0;
2503 }
2504 fg->red = fg->green = fg->blue = fgval;
2505 bg->red = bg->green = bg->blue = bgval;
2506
2507 /* The "Terminal" highlight group overrules the defaults. */
2508 id = syn_name2id((char_u *)"Terminal");
2509
2510 /* Use the actual color for the GUI and when 'guitermcolors' is set. */
2511#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2512 if (0
2513# ifdef FEAT_GUI
2514 || gui.in_use
2515# endif
2516# ifdef FEAT_TERMGUICOLORS
2517 || p_tgc
2518# endif
2519 )
2520 {
2521 guicolor_T fg_rgb = INVALCOLOR;
2522 guicolor_T bg_rgb = INVALCOLOR;
2523
2524 if (id != 0)
2525 syn_id2colors(id, &fg_rgb, &bg_rgb);
2526
2527# ifdef FEAT_GUI
2528 if (gui.in_use)
2529 {
2530 if (fg_rgb == INVALCOLOR)
2531 fg_rgb = gui.norm_pixel;
2532 if (bg_rgb == INVALCOLOR)
2533 bg_rgb = gui.back_pixel;
2534 }
2535# ifdef FEAT_TERMGUICOLORS
2536 else
2537# endif
2538# endif
2539# ifdef FEAT_TERMGUICOLORS
2540 {
2541 if (fg_rgb == INVALCOLOR)
2542 fg_rgb = cterm_normal_fg_gui_color;
2543 if (bg_rgb == INVALCOLOR)
2544 bg_rgb = cterm_normal_bg_gui_color;
2545 }
2546# endif
2547 if (fg_rgb != INVALCOLOR)
2548 {
2549 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2550
2551 fg->red = (unsigned)(rgb >> 16);
2552 fg->green = (unsigned)(rgb >> 8) & 255;
2553 fg->blue = (unsigned)rgb & 255;
2554 }
2555 if (bg_rgb != INVALCOLOR)
2556 {
2557 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2558
2559 bg->red = (unsigned)(rgb >> 16);
2560 bg->green = (unsigned)(rgb >> 8) & 255;
2561 bg->blue = (unsigned)rgb & 255;
2562 }
2563 }
2564 else
2565#endif
2566 if (id != 0 && t_colors >= 16)
2567 {
2568 int cterm_fg, cterm_bg;
2569
2570 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
2571 if (cterm_fg >= 0)
2572 cterm_color2rgb(cterm_fg, fg);
2573 if (cterm_bg >= 0)
2574 cterm_color2rgb(cterm_bg, bg);
2575 }
2576#if defined(WIN3264) && !defined(FEAT_GUI_W32)
2577 else
2578 {
2579 int tmp;
2580
2581 /* In an MS-Windows console we know the normal colors. */
2582 if (cterm_normal_fg_color > 0)
2583 {
2584 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
2585 tmp = fg->red;
2586 fg->red = fg->blue;
2587 fg->blue = tmp;
2588 }
2589 if (cterm_normal_bg_color > 0)
2590 {
2591 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
2592 tmp = bg->red;
2593 bg->red = bg->blue;
2594 bg->blue = tmp;
2595 }
2596 }
2597#endif
2598
2599 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
2600
2601 /* Required to initialize most things. */
2602 vterm_screen_reset(screen, 1 /* hard */);
2603
2604 /* Allow using alternate screen. */
2605 vterm_screen_enable_altscreen(screen, 1);
2606
2607 /* For unix do not use a blinking cursor. In an xterm this causes the
2608 * cursor to blink if it's blinking in the xterm.
2609 * For Windows we respect the system wide setting. */
2610#ifdef WIN3264
2611 if (GetCaretBlinkTime() == INFINITE)
2612 value.boolean = 0;
2613 else
2614 value.boolean = 1;
2615#else
2616 value.boolean = 0;
2617#endif
2618 vterm_state_set_termprop(vterm_obtain_state(vterm),
2619 VTERM_PROP_CURSORBLINK, &value);
2620}
2621
2622/*
2623 * Return the text to show for the buffer name and status.
2624 */
2625 char_u *
2626term_get_status_text(term_T *term)
2627{
2628 if (term->tl_status_text == NULL)
2629 {
2630 char_u *txt;
2631 size_t len;
2632
2633 if (term->tl_normal_mode)
2634 {
2635 if (term_job_running(term))
2636 txt = (char_u *)_("Terminal");
2637 else
2638 txt = (char_u *)_("Terminal-finished");
2639 }
2640 else if (term->tl_title != NULL)
2641 txt = term->tl_title;
2642 else if (term_none_open(term))
2643 txt = (char_u *)_("active");
2644 else if (term_job_running(term))
2645 txt = (char_u *)_("running");
2646 else
2647 txt = (char_u *)_("finished");
2648 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
2649 term->tl_status_text = alloc((int)len);
2650 if (term->tl_status_text != NULL)
2651 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
2652 term->tl_buffer->b_fname, txt);
2653 }
2654 return term->tl_status_text;
2655}
2656
2657/*
2658 * Mark references in jobs of terminals.
2659 */
2660 int
2661set_ref_in_term(int copyID)
2662{
2663 int abort = FALSE;
2664 term_T *term;
2665 typval_T tv;
2666
2667 for (term = first_term; term != NULL; term = term->tl_next)
2668 if (term->tl_job != NULL)
2669 {
2670 tv.v_type = VAR_JOB;
2671 tv.vval.v_job = term->tl_job;
2672 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
2673 }
2674 return abort;
2675}
2676
2677/*
2678 * Get the buffer from the first argument in "argvars".
2679 * Returns NULL when the buffer is not for a terminal window.
2680 */
2681 static buf_T *
2682term_get_buf(typval_T *argvars)
2683{
2684 buf_T *buf;
2685
2686 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2687 ++emsg_off;
2688 buf = get_buf_tv(&argvars[0], FALSE);
2689 --emsg_off;
2690 if (buf == NULL || buf->b_term == NULL)
2691 return NULL;
2692 return buf;
2693}
2694
2695/*
2696 * "term_getaltscreen(buf)" function
2697 */
2698 void
2699f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
2700{
2701 buf_T *buf = term_get_buf(argvars);
2702
2703 if (buf == NULL)
2704 return;
2705 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
2706}
2707
2708/*
2709 * "term_getattr(attr, name)" function
2710 */
2711 void
2712f_term_getattr(typval_T *argvars, typval_T *rettv)
2713{
2714 int attr;
2715 size_t i;
2716 char_u *name;
2717
2718 static struct {
2719 char *name;
2720 int attr;
2721 } attrs[] = {
2722 {"bold", HL_BOLD},
2723 {"italic", HL_ITALIC},
2724 {"underline", HL_UNDERLINE},
2725 {"strike", HL_STRIKETHROUGH},
2726 {"reverse", HL_INVERSE},
2727 };
2728
2729 attr = get_tv_number(&argvars[0]);
2730 name = get_tv_string_chk(&argvars[1]);
2731 if (name == NULL)
2732 return;
2733
2734 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
2735 if (STRCMP(name, attrs[i].name) == 0)
2736 {
2737 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
2738 break;
2739 }
2740}
2741
2742/*
2743 * "term_getcursor(buf)" function
2744 */
2745 void
2746f_term_getcursor(typval_T *argvars, typval_T *rettv)
2747{
2748 buf_T *buf = term_get_buf(argvars);
2749 term_T *term;
2750 list_T *l;
2751 dict_T *d;
2752
2753 if (rettv_list_alloc(rettv) == FAIL)
2754 return;
2755 if (buf == NULL)
2756 return;
2757 term = buf->b_term;
2758
2759 l = rettv->vval.v_list;
2760 list_append_number(l, term->tl_cursor_pos.row + 1);
2761 list_append_number(l, term->tl_cursor_pos.col + 1);
2762
2763 d = dict_alloc();
2764 if (d != NULL)
2765 {
2766 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
2767 dict_add_nr_str(d, "blink", blink_state_is_inverted()
2768 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
2769 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
2770 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
2771 ? (char_u *)"" : term->tl_cursor_color);
2772 list_append_dict(l, d);
2773 }
2774}
2775
2776/*
2777 * "term_getjob(buf)" function
2778 */
2779 void
2780f_term_getjob(typval_T *argvars, typval_T *rettv)
2781{
2782 buf_T *buf = term_get_buf(argvars);
2783
2784 rettv->v_type = VAR_JOB;
2785 rettv->vval.v_job = NULL;
2786 if (buf == NULL)
2787 return;
2788
2789 rettv->vval.v_job = buf->b_term->tl_job;
2790 if (rettv->vval.v_job != NULL)
2791 ++rettv->vval.v_job->jv_refcount;
2792}
2793
2794 static int
2795get_row_number(typval_T *tv, term_T *term)
2796{
2797 if (tv->v_type == VAR_STRING
2798 && tv->vval.v_string != NULL
2799 && STRCMP(tv->vval.v_string, ".") == 0)
2800 return term->tl_cursor_pos.row;
2801 return (int)get_tv_number(tv) - 1;
2802}
2803
2804/*
2805 * "term_getline(buf, row)" function
2806 */
2807 void
2808f_term_getline(typval_T *argvars, typval_T *rettv)
2809{
2810 buf_T *buf = term_get_buf(argvars);
2811 term_T *term;
2812 int row;
2813
2814 rettv->v_type = VAR_STRING;
2815 if (buf == NULL)
2816 return;
2817 term = buf->b_term;
2818 row = get_row_number(&argvars[1], term);
2819
2820 if (term->tl_vterm == NULL)
2821 {
2822 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
2823
2824 /* vterm is finished, get the text from the buffer */
2825 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
2826 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
2827 }
2828 else
2829 {
2830 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
2831 VTermRect rect;
2832 int len;
2833 char_u *p;
2834
2835 if (row < 0 || row >= term->tl_rows)
2836 return;
2837 len = term->tl_cols * MB_MAXBYTES + 1;
2838 p = alloc(len);
2839 if (p == NULL)
2840 return;
2841 rettv->vval.v_string = p;
2842
2843 rect.start_col = 0;
2844 rect.end_col = term->tl_cols;
2845 rect.start_row = row;
2846 rect.end_row = row + 1;
2847 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
2848 }
2849}
2850
2851/*
2852 * "term_getscrolled(buf)" function
2853 */
2854 void
2855f_term_getscrolled(typval_T *argvars, typval_T *rettv)
2856{
2857 buf_T *buf = term_get_buf(argvars);
2858
2859 if (buf == NULL)
2860 return;
2861 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
2862}
2863
2864/*
2865 * "term_getsize(buf)" function
2866 */
2867 void
2868f_term_getsize(typval_T *argvars, typval_T *rettv)
2869{
2870 buf_T *buf = term_get_buf(argvars);
2871 list_T *l;
2872
2873 if (rettv_list_alloc(rettv) == FAIL)
2874 return;
2875 if (buf == NULL)
2876 return;
2877
2878 l = rettv->vval.v_list;
2879 list_append_number(l, buf->b_term->tl_rows);
2880 list_append_number(l, buf->b_term->tl_cols);
2881}
2882
2883/*
2884 * "term_getstatus(buf)" function
2885 */
2886 void
2887f_term_getstatus(typval_T *argvars, typval_T *rettv)
2888{
2889 buf_T *buf = term_get_buf(argvars);
2890 term_T *term;
2891 char_u val[100];
2892
2893 rettv->v_type = VAR_STRING;
2894 if (buf == NULL)
2895 return;
2896 term = buf->b_term;
2897
2898 if (term_job_running(term))
2899 STRCPY(val, "running");
2900 else
2901 STRCPY(val, "finished");
2902 if (term->tl_normal_mode)
2903 STRCAT(val, ",normal");
2904 rettv->vval.v_string = vim_strsave(val);
2905}
2906
2907/*
2908 * "term_gettitle(buf)" function
2909 */
2910 void
2911f_term_gettitle(typval_T *argvars, typval_T *rettv)
2912{
2913 buf_T *buf = term_get_buf(argvars);
2914
2915 rettv->v_type = VAR_STRING;
2916 if (buf == NULL)
2917 return;
2918
2919 if (buf->b_term->tl_title != NULL)
2920 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
2921}
2922
2923/*
2924 * "term_gettty(buf)" function
2925 */
2926 void
2927f_term_gettty(typval_T *argvars, typval_T *rettv)
2928{
2929 buf_T *buf = term_get_buf(argvars);
2930 char_u *p;
2931 int num = 0;
2932
2933 rettv->v_type = VAR_STRING;
2934 if (buf == NULL)
2935 return;
2936 if (argvars[1].v_type != VAR_UNKNOWN)
2937 num = get_tv_number(&argvars[1]);
2938
2939 switch (num)
2940 {
2941 case 0:
2942 if (buf->b_term->tl_job != NULL)
2943 p = buf->b_term->tl_job->jv_tty_out;
2944 else
2945 p = buf->b_term->tl_tty_out;
2946 break;
2947 case 1:
2948 if (buf->b_term->tl_job != NULL)
2949 p = buf->b_term->tl_job->jv_tty_in;
2950 else
2951 p = buf->b_term->tl_tty_in;
2952 break;
2953 default:
2954 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
2955 return;
2956 }
2957 if (p != NULL)
2958 rettv->vval.v_string = vim_strsave(p);
2959}
2960
2961/*
2962 * "term_list()" function
2963 */
2964 void
2965f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
2966{
2967 term_T *tp;
2968 list_T *l;
2969
2970 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
2971 return;
2972
2973 l = rettv->vval.v_list;
2974 for (tp = first_term; tp != NULL; tp = tp->tl_next)
2975 if (tp != NULL && tp->tl_buffer != NULL)
2976 if (list_append_number(l,
2977 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
2978 return;
2979}
2980
2981/*
2982 * "term_scrape(buf, row)" function
2983 */
2984 void
2985f_term_scrape(typval_T *argvars, typval_T *rettv)
2986{
2987 buf_T *buf = term_get_buf(argvars);
2988 VTermScreen *screen = NULL;
2989 VTermPos pos;
2990 list_T *l;
2991 term_T *term;
2992 char_u *p;
2993 sb_line_T *line;
2994
2995 if (rettv_list_alloc(rettv) == FAIL)
2996 return;
2997 if (buf == NULL)
2998 return;
2999 term = buf->b_term;
3000
3001 l = rettv->vval.v_list;
3002 pos.row = get_row_number(&argvars[1], term);
3003
3004 if (term->tl_vterm != NULL)
3005 {
3006 screen = vterm_obtain_screen(term->tl_vterm);
3007 p = NULL;
3008 line = NULL;
3009 }
3010 else
3011 {
3012 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3013
3014 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3015 return;
3016 p = ml_get_buf(buf, lnum + 1, FALSE);
3017 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3018 }
3019
3020 for (pos.col = 0; pos.col < term->tl_cols; )
3021 {
3022 dict_T *dcell;
3023 int width;
3024 VTermScreenCellAttrs attrs;
3025 VTermColor fg, bg;
3026 char_u rgb[8];
3027 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3028 int off = 0;
3029 int i;
3030
3031 if (screen == NULL)
3032 {
3033 cellattr_T *cellattr;
3034 int len;
3035
3036 /* vterm has finished, get the cell from scrollback */
3037 if (pos.col >= line->sb_cols)
3038 break;
3039 cellattr = line->sb_cells + pos.col;
3040 width = cellattr->width;
3041 attrs = cellattr->attrs;
3042 fg = cellattr->fg;
3043 bg = cellattr->bg;
3044 len = MB_PTR2LEN(p);
3045 mch_memmove(mbs, p, len);
3046 mbs[len] = NUL;
3047 p += len;
3048 }
3049 else
3050 {
3051 VTermScreenCell cell;
3052 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3053 break;
3054 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3055 {
3056 if (cell.chars[i] == 0)
3057 break;
3058 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3059 }
3060 mbs[off] = NUL;
3061 width = cell.width;
3062 attrs = cell.attrs;
3063 fg = cell.fg;
3064 bg = cell.bg;
3065 }
3066 dcell = dict_alloc();
3067 list_append_dict(l, dcell);
3068
3069 dict_add_nr_str(dcell, "chars", 0, mbs);
3070
3071 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3072 fg.red, fg.green, fg.blue);
3073 dict_add_nr_str(dcell, "fg", 0, rgb);
3074 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3075 bg.red, bg.green, bg.blue);
3076 dict_add_nr_str(dcell, "bg", 0, rgb);
3077
3078 dict_add_nr_str(dcell, "attr",
3079 cell2attr(attrs, fg, bg), NULL);
3080 dict_add_nr_str(dcell, "width", width, NULL);
3081
3082 ++pos.col;
3083 if (width == 2)
3084 ++pos.col;
3085 }
3086}
3087
3088/*
3089 * "term_sendkeys(buf, keys)" function
3090 */
3091 void
3092f_term_sendkeys(typval_T *argvars, typval_T *rettv)
3093{
3094 buf_T *buf = term_get_buf(argvars);
3095 char_u *msg;
3096 term_T *term;
3097
3098 rettv->v_type = VAR_UNKNOWN;
3099 if (buf == NULL)
3100 return;
3101
3102 msg = get_tv_string_chk(&argvars[1]);
3103 if (msg == NULL)
3104 return;
3105 term = buf->b_term;
3106 if (term->tl_vterm == NULL)
3107 return;
3108
3109 while (*msg != NUL)
3110 {
3111 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
3112 msg += MB_PTR2LEN(msg);
3113 }
3114}
3115
3116/*
3117 * "term_start(command, options)" function
3118 */
3119 void
3120f_term_start(typval_T *argvars, typval_T *rettv)
3121{
3122 jobopt_T opt;
3123 buf_T *buf;
3124
3125 init_job_options(&opt);
3126 if (argvars[1].v_type != VAR_UNKNOWN
3127 && get_job_options(&argvars[1], &opt,
3128 JO_TIMEOUT_ALL + JO_STOPONEXIT
3129 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
3130 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
3131 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
3132 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
3133 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
3134 return;
3135
3136 if (opt.jo_vertical)
3137 cmdmod.split = WSP_VERT;
3138 buf = term_start(&argvars[0], &opt, FALSE);
3139
3140 if (buf != NULL && buf->b_term != NULL)
3141 rettv->vval.v_number = buf->b_fnum;
3142}
3143
3144/*
3145 * "term_wait" function
3146 */
3147 void
3148f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
3149{
3150 buf_T *buf = term_get_buf(argvars);
3151
3152 if (buf == NULL)
3153 {
3154 ch_log(NULL, "term_wait(): invalid argument");
3155 return;
3156 }
3157 if (buf->b_term->tl_job == NULL)
3158 {
3159 ch_log(NULL, "term_wait(): no job to wait for");
3160 return;
3161 }
3162 if (buf->b_term->tl_job->jv_channel == NULL)
3163 /* channel is closed, nothing to do */
3164 return;
3165
3166 /* Get the job status, this will detect a job that finished. */
3167 if ((buf->b_term->tl_job->jv_channel == NULL
3168 || !buf->b_term->tl_job->jv_channel->ch_keep_open)
3169 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
3170 {
3171 /* The job is dead, keep reading channel I/O until the channel is
3172 * closed. buf->b_term may become NULL if the terminal was closed while
3173 * waiting. */
3174 ch_log(NULL, "term_wait(): waiting for channel to close");
3175 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
3176 {
3177 mch_check_messages();
3178 parse_queued_messages();
3179 ui_delay(10L, FALSE);
3180 }
3181 mch_check_messages();
3182 parse_queued_messages();
3183 }
3184 else
3185 {
3186 long wait = 10L;
3187
3188 mch_check_messages();
3189 parse_queued_messages();
3190
3191 /* Wait for some time for any channel I/O. */
3192 if (argvars[1].v_type != VAR_UNKNOWN)
3193 wait = get_tv_number(&argvars[1]);
3194 ui_delay(wait, TRUE);
3195 mch_check_messages();
3196
3197 /* Flushing messages on channels is hopefully sufficient.
3198 * TODO: is there a better way? */
3199 parse_queued_messages();
3200 }
3201}
3202
3203/*
3204 * Called when a channel has sent all the lines to a terminal.
3205 * Send a CTRL-D to mark the end of the text.
3206 */
3207 void
3208term_send_eof(channel_T *ch)
3209{
3210 term_T *term;
3211
3212 for (term = first_term; term != NULL; term = term->tl_next)
3213 if (term->tl_job == ch->ch_job)
3214 {
3215 if (term->tl_eof_chars != NULL)
3216 {
3217 channel_send(ch, PART_IN, term->tl_eof_chars,
3218 (int)STRLEN(term->tl_eof_chars), NULL);
3219 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
3220 }
3221# ifdef WIN3264
3222 else
3223 /* Default: CTRL-D */
3224 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
3225# endif
3226 }
3227}
3228
3229# if defined(WIN3264) || defined(PROTO)
3230
3231/**************************************
3232 * 2. MS-Windows implementation.
3233 */
3234
3235# ifndef PROTO
3236
3237#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
3238#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
3239#define WINPTY_MOUSE_MODE_FORCE 2
3240
3241void* (*winpty_config_new)(UINT64, void*);
3242void* (*winpty_open)(void*, void*);
3243void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
3244BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
3245void (*winpty_config_set_mouse_mode)(void*, int);
3246void (*winpty_config_set_initial_size)(void*, int, int);
3247LPCWSTR (*winpty_conin_name)(void*);
3248LPCWSTR (*winpty_conout_name)(void*);
3249LPCWSTR (*winpty_conerr_name)(void*);
3250void (*winpty_free)(void*);
3251void (*winpty_config_free)(void*);
3252void (*winpty_spawn_config_free)(void*);
3253void (*winpty_error_free)(void*);
3254LPCWSTR (*winpty_error_msg)(void*);
3255BOOL (*winpty_set_size)(void*, int, int, void*);
3256HANDLE (*winpty_agent_process)(void*);
3257
3258#define WINPTY_DLL "winpty.dll"
3259
3260static HINSTANCE hWinPtyDLL = NULL;
3261# endif
3262
3263 static int
3264dyn_winpty_init(int verbose)
3265{
3266 int i;
3267 static struct
3268 {
3269 char *name;
3270 FARPROC *ptr;
3271 } winpty_entry[] =
3272 {
3273 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
3274 {"winpty_config_free", (FARPROC*)&winpty_config_free},
3275 {"winpty_config_new", (FARPROC*)&winpty_config_new},
3276 {"winpty_config_set_mouse_mode",
3277 (FARPROC*)&winpty_config_set_mouse_mode},
3278 {"winpty_config_set_initial_size",
3279 (FARPROC*)&winpty_config_set_initial_size},
3280 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
3281 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
3282 {"winpty_error_free", (FARPROC*)&winpty_error_free},
3283 {"winpty_free", (FARPROC*)&winpty_free},
3284 {"winpty_open", (FARPROC*)&winpty_open},
3285 {"winpty_spawn", (FARPROC*)&winpty_spawn},
3286 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
3287 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
3288 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
3289 {"winpty_set_size", (FARPROC*)&winpty_set_size},
3290 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
3291 {NULL, NULL}
3292 };
3293
3294 /* No need to initialize twice. */
3295 if (hWinPtyDLL)
3296 return OK;
3297 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
3298 * winpty.dll. */
3299 if (*p_winptydll != NUL)
3300 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
3301 if (!hWinPtyDLL)
3302 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
3303 if (!hWinPtyDLL)
3304 {
3305 if (verbose)
3306 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
3307 : (char_u *)WINPTY_DLL);
3308 return FAIL;
3309 }
3310 for (i = 0; winpty_entry[i].name != NULL
3311 && winpty_entry[i].ptr != NULL; ++i)
3312 {
3313 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
3314 winpty_entry[i].name)) == NULL)
3315 {
3316 if (verbose)
3317 EMSG2(_(e_loadfunc), winpty_entry[i].name);
3318 return FAIL;
3319 }
3320 }
3321
3322 return OK;
3323}
3324
3325/*
3326 * Create a new terminal of "rows" by "cols" cells.
3327 * Store a reference in "term".
3328 * Return OK or FAIL.
3329 */
3330 static int
3331term_and_job_init(
3332 term_T *term,
3333 typval_T *argvar,
3334 jobopt_T *opt)
3335{
3336 WCHAR *cmd_wchar = NULL;
3337 WCHAR *cwd_wchar = NULL;
3338 channel_T *channel = NULL;
3339 job_T *job = NULL;
3340 DWORD error;
3341 HANDLE jo = NULL;
3342 HANDLE child_process_handle;
3343 HANDLE child_thread_handle;
3344 void *winpty_err;
3345 void *spawn_config = NULL;
3346 garray_T ga;
3347 char_u *cmd;
3348
3349 if (dyn_winpty_init(TRUE) == FAIL)
3350 return FAIL;
3351
3352 if (argvar->v_type == VAR_STRING)
3353 cmd = argvar->vval.v_string;
3354 else
3355 {
3356 ga_init2(&ga, (int)sizeof(char*), 20);
3357 if (win32_build_cmd(argvar->vval.v_list, &ga) == FAIL)
3358 goto failed;
3359 cmd = ga.ga_data;
3360 }
3361
3362 cmd_wchar = enc_to_utf16(cmd, NULL);
3363 if (cmd_wchar == NULL)
3364 return FAIL;
3365 if (opt->jo_cwd != NULL)
3366 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
3367
3368 job = job_alloc();
3369 if (job == NULL)
3370 goto failed;
3371
3372 channel = add_channel();
3373 if (channel == NULL)
3374 goto failed;
3375
3376 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
3377 if (term->tl_winpty_config == NULL)
3378 goto failed;
3379
3380 winpty_config_set_mouse_mode(term->tl_winpty_config,
3381 WINPTY_MOUSE_MODE_FORCE);
3382 winpty_config_set_initial_size(term->tl_winpty_config,
3383 term->tl_cols, term->tl_rows);
3384 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
3385 if (term->tl_winpty == NULL)
3386 goto failed;
3387
3388 spawn_config = winpty_spawn_config_new(
3389 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
3390 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
3391 NULL,
3392 cmd_wchar,
3393 cwd_wchar,
3394 NULL,
3395 &winpty_err);
3396 if (spawn_config == NULL)
3397 goto failed;
3398
3399 channel = add_channel();
3400 if (channel == NULL)
3401 goto failed;
3402
3403 job = job_alloc();
3404 if (job == NULL)
3405 goto failed;
3406
3407 if (opt->jo_set & JO_IN_BUF)
3408 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
3409
3410 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
3411 &child_thread_handle, &error, &winpty_err))
3412 goto failed;
3413
3414 channel_set_pipes(channel,
3415 (sock_T)CreateFileW(
3416 winpty_conin_name(term->tl_winpty),
3417 GENERIC_WRITE, 0, NULL,
3418 OPEN_EXISTING, 0, NULL),
3419 (sock_T)CreateFileW(
3420 winpty_conout_name(term->tl_winpty),
3421 GENERIC_READ, 0, NULL,
3422 OPEN_EXISTING, 0, NULL),
3423 (sock_T)CreateFileW(
3424 winpty_conerr_name(term->tl_winpty),
3425 GENERIC_READ, 0, NULL,
3426 OPEN_EXISTING, 0, NULL));
3427
3428 /* Write lines with CR instead of NL. */
3429 channel->ch_write_text_mode = TRUE;
3430
3431 jo = CreateJobObject(NULL, NULL);
3432 if (jo == NULL)
3433 goto failed;
3434
3435 if (!AssignProcessToJobObject(jo, child_process_handle))
3436 {
3437 /* Failed, switch the way to terminate process with TerminateProcess. */
3438 CloseHandle(jo);
3439 jo = NULL;
3440 }
3441
3442 winpty_spawn_config_free(spawn_config);
3443 vim_free(cmd_wchar);
3444 vim_free(cwd_wchar);
3445
3446 create_vterm(term, term->tl_rows, term->tl_cols);
3447
3448 channel_set_job(channel, job, opt);
3449 job_set_options(job, opt);
3450
3451 job->jv_channel = channel;
3452 job->jv_proc_info.hProcess = child_process_handle;
3453 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
3454 job->jv_job_object = jo;
3455 job->jv_status = JOB_STARTED;
3456 job->jv_tty_in = utf16_to_enc(
3457 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
3458 job->jv_tty_out = utf16_to_enc(
3459 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
3460 ++job->jv_refcount;
3461 term->tl_job = job;
3462
3463 return OK;
3464
3465failed:
3466 if (argvar->v_type == VAR_LIST)
3467 vim_free(ga.ga_data);
3468 vim_free(cmd_wchar);
3469 vim_free(cwd_wchar);
3470 if (spawn_config != NULL)
3471 winpty_spawn_config_free(spawn_config);
3472 if (channel != NULL)
3473 channel_clear(channel);
3474 if (job != NULL)
3475 {
3476 job->jv_channel = NULL;
3477 job_cleanup(job);
3478 }
3479 term->tl_job = NULL;
3480 if (jo != NULL)
3481 CloseHandle(jo);
3482 if (term->tl_winpty != NULL)
3483 winpty_free(term->tl_winpty);
3484 term->tl_winpty = NULL;
3485 if (term->tl_winpty_config != NULL)
3486 winpty_config_free(term->tl_winpty_config);
3487 term->tl_winpty_config = NULL;
3488 if (winpty_err != NULL)
3489 {
3490 char_u *msg = utf16_to_enc(
3491 (short_u *)winpty_error_msg(winpty_err), NULL);
3492
3493 EMSG(msg);
3494 winpty_error_free(winpty_err);
3495 }
3496 return FAIL;
3497}
3498
3499 static int
3500create_pty_only(term_T *term, jobopt_T *options)
3501{
3502 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
3503 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
3504 char in_name[80], out_name[80];
3505 channel_T *channel = NULL;
3506
3507 create_vterm(term, term->tl_rows, term->tl_cols);
3508
3509 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
3510 GetCurrentProcessId(),
3511 curbuf->b_fnum);
3512 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
3513 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3514 PIPE_UNLIMITED_INSTANCES,
3515 0, 0, NMPWAIT_NOWAIT, NULL);
3516 if (hPipeIn == INVALID_HANDLE_VALUE)
3517 goto failed;
3518
3519 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
3520 GetCurrentProcessId(),
3521 curbuf->b_fnum);
3522 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
3523 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3524 PIPE_UNLIMITED_INSTANCES,
3525 0, 0, 0, NULL);
3526 if (hPipeOut == INVALID_HANDLE_VALUE)
3527 goto failed;
3528
3529 ConnectNamedPipe(hPipeIn, NULL);
3530 ConnectNamedPipe(hPipeOut, NULL);
3531
3532 term->tl_job = job_alloc();
3533 if (term->tl_job == NULL)
3534 goto failed;
3535 ++term->tl_job->jv_refcount;
3536
3537 /* behave like the job is already finished */
3538 term->tl_job->jv_status = JOB_FINISHED;
3539
3540 channel = add_channel();
3541 if (channel == NULL)
3542 goto failed;
3543 term->tl_job->jv_channel = channel;
3544 channel->ch_keep_open = TRUE;
3545 channel->ch_named_pipe = TRUE;
3546
3547 channel_set_pipes(channel,
3548 (sock_T)hPipeIn,
3549 (sock_T)hPipeOut,
3550 (sock_T)hPipeOut);
3551 channel_set_job(channel, term->tl_job, options);
3552 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
3553 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
3554
3555 return OK;
3556
3557failed:
3558 if (hPipeIn != NULL)
3559 CloseHandle(hPipeIn);
3560 if (hPipeOut != NULL)
3561 CloseHandle(hPipeOut);
3562 return FAIL;
3563}
3564
3565/*
3566 * Free the terminal emulator part of "term".
3567 */
3568 static void
3569term_free_vterm(term_T *term)
3570{
3571 if (term->tl_winpty != NULL)
3572 winpty_free(term->tl_winpty);
3573 term->tl_winpty = NULL;
3574 if (term->tl_winpty_config != NULL)
3575 winpty_config_free(term->tl_winpty_config);
3576 term->tl_winpty_config = NULL;
3577 if (term->tl_vterm != NULL)
3578 vterm_free(term->tl_vterm);
3579 term->tl_vterm = NULL;
3580}
3581
3582/*
3583 * Request size to terminal.
3584 */
3585 static void
3586term_report_winsize(term_T *term, int rows, int cols)
3587{
3588 if (term->tl_winpty)
3589 winpty_set_size(term->tl_winpty, cols, rows, NULL);
3590}
3591
3592 int
3593terminal_enabled(void)
3594{
3595 return dyn_winpty_init(FALSE) == OK;
3596}
3597
3598# else
3599
3600/**************************************
3601 * 3. Unix-like implementation.
3602 */
3603
3604/*
3605 * Create a new terminal of "rows" by "cols" cells.
3606 * Start job for "cmd".
3607 * Store the pointers in "term".
3608 * Return OK or FAIL.
3609 */
3610 static int
3611term_and_job_init(
3612 term_T *term,
3613 typval_T *argvar,
3614 jobopt_T *opt)
3615{
3616 create_vterm(term, term->tl_rows, term->tl_cols);
3617
3618 term->tl_job = job_start(argvar, opt);
3619 if (term->tl_job != NULL)
3620 ++term->tl_job->jv_refcount;
3621
3622 return term->tl_job != NULL
3623 && term->tl_job->jv_channel != NULL
3624 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
3625}
3626
3627 static int
3628create_pty_only(term_T *term, jobopt_T *opt)
3629{
3630 create_vterm(term, term->tl_rows, term->tl_cols);
3631
3632 term->tl_job = job_alloc();
3633 if (term->tl_job == NULL)
3634 return FAIL;
3635 ++term->tl_job->jv_refcount;
3636
3637 /* behave like the job is already finished */
3638 term->tl_job->jv_status = JOB_FINISHED;
3639
3640 return mch_create_pty_channel(term->tl_job, opt);
3641}
3642
3643/*
3644 * Free the terminal emulator part of "term".
3645 */
3646 static void
3647term_free_vterm(term_T *term)
3648{
3649 if (term->tl_vterm != NULL)
3650 vterm_free(term->tl_vterm);
3651 term->tl_vterm = NULL;
3652}
3653
3654/*
3655 * Request size to terminal.
3656 */
3657 static void
3658term_report_winsize(term_T *term, int rows, int cols)
3659{
3660 /* Use an ioctl() to report the new window size to the job. */
3661 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
3662 {
3663 int fd = -1;
3664 int part;
3665
3666 for (part = PART_OUT; part < PART_COUNT; ++part)
3667 {
3668 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
3669 if (isatty(fd))
3670 break;
3671 }
3672 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
3673 mch_signal_job(term->tl_job, (char_u *)"winch");
3674 }
3675}
3676
3677# endif
3678
3679#endif /* FEAT_TERMINAL */