comparison src/terminal.c @ 12502:ed85dd1b8c80

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