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