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