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