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