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