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