xref: /openbsd-src/usr.bin/tmux/input.c (revision eb1b93f95d68c8a362dbd50b0d6814511573e654)
1 /* $OpenBSD: input.c,v 1.220 2023/08/23 08:30:07 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 
21 #include <netinet/in.h>
22 
23 #include <ctype.h>
24 #include <resolv.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <time.h>
28 
29 #include "tmux.h"
30 
31 /*
32  * Based on the description by Paul Williams at:
33  *
34  * https://vt100.net/emu/dec_ansi_parser
35  *
36  * With the following changes:
37  *
38  * - 7-bit only.
39  *
40  * - Support for UTF-8.
41  *
42  * - OSC (but not APC) may be terminated by \007 as well as ST.
43  *
44  * - A state for APC similar to OSC. Some terminals appear to use this to set
45  *   the title.
46  *
47  * - A state for the screen \033k...\033\\ sequence to rename a window. This is
48  *   pretty stupid but not supporting it is more trouble than it is worth.
49  *
50  * - Special handling for ESC inside a DCS to allow arbitrary byte sequences to
51  *   be passed to the underlying terminals.
52  */
53 
54 /* Input parser cell. */
55 struct input_cell {
56 	struct grid_cell	cell;
57 	int			set;
58 	int			g0set;	/* 1 if ACS */
59 	int			g1set;	/* 1 if ACS */
60 };
61 
62 /* Input parser argument. */
63 struct input_param {
64 	enum {
65 		INPUT_MISSING,
66 		INPUT_NUMBER,
67 		INPUT_STRING
68 	}			type;
69 	union {
70 		int		num;
71 		char	       *str;
72 	};
73 };
74 
75 /* Input parser context. */
76 struct input_ctx {
77 	struct window_pane     *wp;
78 	struct bufferevent     *event;
79 	struct screen_write_ctx ctx;
80 	struct colour_palette  *palette;
81 
82 	struct input_cell	cell;
83 
84 	struct input_cell	old_cell;
85 	u_int			old_cx;
86 	u_int			old_cy;
87 	int			old_mode;
88 
89 	u_char			interm_buf[4];
90 	size_t			interm_len;
91 
92 	u_char			param_buf[64];
93 	size_t			param_len;
94 
95 #define INPUT_BUF_START 32
96 #define INPUT_BUF_LIMIT 1048576
97 	u_char		       *input_buf;
98 	size_t			input_len;
99 	size_t			input_space;
100 	enum {
101 		INPUT_END_ST,
102 		INPUT_END_BEL
103 	}			input_end;
104 
105 	struct input_param	param_list[24];
106 	u_int			param_list_len;
107 
108 	struct utf8_data	utf8data;
109 	int			utf8started;
110 
111 	int			ch;
112 	int			last;
113 
114 	int			flags;
115 #define INPUT_DISCARD 0x1
116 
117 	const struct input_state *state;
118 
119 	struct event		timer;
120 
121 	/*
122 	 * All input received since we were last in the ground state. Sent to
123 	 * control clients on connection.
124 	 */
125 	struct evbuffer		*since_ground;
126 };
127 
128 /* Helper functions. */
129 struct input_transition;
130 static int	input_split(struct input_ctx *);
131 static int	input_get(struct input_ctx *, u_int, int, int);
132 static void printflike(2, 3) input_reply(struct input_ctx *, const char *, ...);
133 static void	input_set_state(struct input_ctx *,
134 		    const struct input_transition *);
135 static void	input_reset_cell(struct input_ctx *);
136 
137 static void	input_osc_4(struct input_ctx *, const char *);
138 static void	input_osc_8(struct input_ctx *, const char *);
139 static void	input_osc_10(struct input_ctx *, const char *);
140 static void	input_osc_11(struct input_ctx *, const char *);
141 static void	input_osc_12(struct input_ctx *, const char *);
142 static void	input_osc_52(struct input_ctx *, const char *);
143 static void	input_osc_104(struct input_ctx *, const char *);
144 static void	input_osc_110(struct input_ctx *, const char *);
145 static void	input_osc_111(struct input_ctx *, const char *);
146 static void	input_osc_112(struct input_ctx *, const char *);
147 static void	input_osc_133(struct input_ctx *, const char *);
148 
149 /* Transition entry/exit handlers. */
150 static void	input_clear(struct input_ctx *);
151 static void	input_ground(struct input_ctx *);
152 static void	input_enter_dcs(struct input_ctx *);
153 static void	input_enter_osc(struct input_ctx *);
154 static void	input_exit_osc(struct input_ctx *);
155 static void	input_enter_apc(struct input_ctx *);
156 static void	input_exit_apc(struct input_ctx *);
157 static void	input_enter_rename(struct input_ctx *);
158 static void	input_exit_rename(struct input_ctx *);
159 
160 /* Input state handlers. */
161 static int	input_print(struct input_ctx *);
162 static int	input_intermediate(struct input_ctx *);
163 static int	input_parameter(struct input_ctx *);
164 static int	input_input(struct input_ctx *);
165 static int	input_c0_dispatch(struct input_ctx *);
166 static int	input_esc_dispatch(struct input_ctx *);
167 static int	input_csi_dispatch(struct input_ctx *);
168 static void	input_csi_dispatch_rm(struct input_ctx *);
169 static void	input_csi_dispatch_rm_private(struct input_ctx *);
170 static void	input_csi_dispatch_sm(struct input_ctx *);
171 static void	input_csi_dispatch_sm_private(struct input_ctx *);
172 static void	input_csi_dispatch_winops(struct input_ctx *);
173 static void	input_csi_dispatch_sgr_256(struct input_ctx *, int, u_int *);
174 static void	input_csi_dispatch_sgr_rgb(struct input_ctx *, int, u_int *);
175 static void	input_csi_dispatch_sgr(struct input_ctx *);
176 static int	input_dcs_dispatch(struct input_ctx *);
177 static int	input_top_bit_set(struct input_ctx *);
178 static int	input_end_bel(struct input_ctx *);
179 
180 /* Command table comparison function. */
181 static int	input_table_compare(const void *, const void *);
182 
183 /* Command table entry. */
184 struct input_table_entry {
185 	int		ch;
186 	const char     *interm;
187 	int		type;
188 };
189 
190 /* Escape commands. */
191 enum input_esc_type {
192 	INPUT_ESC_DECALN,
193 	INPUT_ESC_DECKPAM,
194 	INPUT_ESC_DECKPNM,
195 	INPUT_ESC_DECRC,
196 	INPUT_ESC_DECSC,
197 	INPUT_ESC_HTS,
198 	INPUT_ESC_IND,
199 	INPUT_ESC_NEL,
200 	INPUT_ESC_RI,
201 	INPUT_ESC_RIS,
202 	INPUT_ESC_SCSG0_OFF,
203 	INPUT_ESC_SCSG0_ON,
204 	INPUT_ESC_SCSG1_OFF,
205 	INPUT_ESC_SCSG1_ON,
206 	INPUT_ESC_ST,
207 };
208 
209 /* Escape command table. */
210 static const struct input_table_entry input_esc_table[] = {
211 	{ '0', "(", INPUT_ESC_SCSG0_ON },
212 	{ '0', ")", INPUT_ESC_SCSG1_ON },
213 	{ '7', "",  INPUT_ESC_DECSC },
214 	{ '8', "",  INPUT_ESC_DECRC },
215 	{ '8', "#", INPUT_ESC_DECALN },
216 	{ '=', "",  INPUT_ESC_DECKPAM },
217 	{ '>', "",  INPUT_ESC_DECKPNM },
218 	{ 'B', "(", INPUT_ESC_SCSG0_OFF },
219 	{ 'B', ")", INPUT_ESC_SCSG1_OFF },
220 	{ 'D', "",  INPUT_ESC_IND },
221 	{ 'E', "",  INPUT_ESC_NEL },
222 	{ 'H', "",  INPUT_ESC_HTS },
223 	{ 'M', "",  INPUT_ESC_RI },
224 	{ '\\', "", INPUT_ESC_ST },
225 	{ 'c', "",  INPUT_ESC_RIS },
226 };
227 
228 /* Control (CSI) commands. */
229 enum input_csi_type {
230 	INPUT_CSI_CBT,
231 	INPUT_CSI_CNL,
232 	INPUT_CSI_CPL,
233 	INPUT_CSI_CUB,
234 	INPUT_CSI_CUD,
235 	INPUT_CSI_CUF,
236 	INPUT_CSI_CUP,
237 	INPUT_CSI_CUU,
238 	INPUT_CSI_DA,
239 	INPUT_CSI_DA_TWO,
240 	INPUT_CSI_DCH,
241 	INPUT_CSI_DECSCUSR,
242 	INPUT_CSI_DECSTBM,
243 	INPUT_CSI_DL,
244 	INPUT_CSI_DSR,
245 	INPUT_CSI_ECH,
246 	INPUT_CSI_ED,
247 	INPUT_CSI_EL,
248 	INPUT_CSI_HPA,
249 	INPUT_CSI_ICH,
250 	INPUT_CSI_IL,
251 	INPUT_CSI_MODOFF,
252 	INPUT_CSI_MODSET,
253 	INPUT_CSI_RCP,
254 	INPUT_CSI_REP,
255 	INPUT_CSI_RM,
256 	INPUT_CSI_RM_PRIVATE,
257 	INPUT_CSI_SCP,
258 	INPUT_CSI_SD,
259 	INPUT_CSI_SGR,
260 	INPUT_CSI_SM,
261 	INPUT_CSI_SM_PRIVATE,
262 	INPUT_CSI_SU,
263 	INPUT_CSI_TBC,
264 	INPUT_CSI_VPA,
265 	INPUT_CSI_WINOPS,
266 	INPUT_CSI_XDA,
267 };
268 
269 /* Control (CSI) command table. */
270 static const struct input_table_entry input_csi_table[] = {
271 	{ '@', "",  INPUT_CSI_ICH },
272 	{ 'A', "",  INPUT_CSI_CUU },
273 	{ 'B', "",  INPUT_CSI_CUD },
274 	{ 'C', "",  INPUT_CSI_CUF },
275 	{ 'D', "",  INPUT_CSI_CUB },
276 	{ 'E', "",  INPUT_CSI_CNL },
277 	{ 'F', "",  INPUT_CSI_CPL },
278 	{ 'G', "",  INPUT_CSI_HPA },
279 	{ 'H', "",  INPUT_CSI_CUP },
280 	{ 'J', "",  INPUT_CSI_ED },
281 	{ 'K', "",  INPUT_CSI_EL },
282 	{ 'L', "",  INPUT_CSI_IL },
283 	{ 'M', "",  INPUT_CSI_DL },
284 	{ 'P', "",  INPUT_CSI_DCH },
285 	{ 'S', "",  INPUT_CSI_SU },
286 	{ 'T', "",  INPUT_CSI_SD },
287 	{ 'X', "",  INPUT_CSI_ECH },
288 	{ 'Z', "",  INPUT_CSI_CBT },
289 	{ '`', "",  INPUT_CSI_HPA },
290 	{ 'b', "",  INPUT_CSI_REP },
291 	{ 'c', "",  INPUT_CSI_DA },
292 	{ 'c', ">", INPUT_CSI_DA_TWO },
293 	{ 'd', "",  INPUT_CSI_VPA },
294 	{ 'f', "",  INPUT_CSI_CUP },
295 	{ 'g', "",  INPUT_CSI_TBC },
296 	{ 'h', "",  INPUT_CSI_SM },
297 	{ 'h', "?", INPUT_CSI_SM_PRIVATE },
298 	{ 'l', "",  INPUT_CSI_RM },
299 	{ 'l', "?", INPUT_CSI_RM_PRIVATE },
300 	{ 'm', "",  INPUT_CSI_SGR },
301 	{ 'm', ">", INPUT_CSI_MODSET },
302 	{ 'n', "",  INPUT_CSI_DSR },
303 	{ 'n', ">", INPUT_CSI_MODOFF },
304 	{ 'q', " ", INPUT_CSI_DECSCUSR },
305 	{ 'q', ">", INPUT_CSI_XDA },
306 	{ 'r', "",  INPUT_CSI_DECSTBM },
307 	{ 's', "",  INPUT_CSI_SCP },
308 	{ 't', "",  INPUT_CSI_WINOPS },
309 	{ 'u', "",  INPUT_CSI_RCP },
310 };
311 
312 /* Input transition. */
313 struct input_transition {
314 	int				first;
315 	int				last;
316 
317 	int				(*handler)(struct input_ctx *);
318 	const struct input_state       *state;
319 };
320 
321 /* Input state. */
322 struct input_state {
323 	const char			*name;
324 	void				(*enter)(struct input_ctx *);
325 	void				(*exit)(struct input_ctx *);
326 	const struct input_transition	*transitions;
327 };
328 
329 /* State transitions available from all states. */
330 #define INPUT_STATE_ANYWHERE \
331 	{ 0x18, 0x18, input_c0_dispatch, &input_state_ground }, \
332 	{ 0x1a, 0x1a, input_c0_dispatch, &input_state_ground }, \
333 	{ 0x1b, 0x1b, NULL,		 &input_state_esc_enter }
334 
335 /* Forward declarations of state tables. */
336 static const struct input_transition input_state_ground_table[];
337 static const struct input_transition input_state_esc_enter_table[];
338 static const struct input_transition input_state_esc_intermediate_table[];
339 static const struct input_transition input_state_csi_enter_table[];
340 static const struct input_transition input_state_csi_parameter_table[];
341 static const struct input_transition input_state_csi_intermediate_table[];
342 static const struct input_transition input_state_csi_ignore_table[];
343 static const struct input_transition input_state_dcs_enter_table[];
344 static const struct input_transition input_state_dcs_parameter_table[];
345 static const struct input_transition input_state_dcs_intermediate_table[];
346 static const struct input_transition input_state_dcs_handler_table[];
347 static const struct input_transition input_state_dcs_escape_table[];
348 static const struct input_transition input_state_dcs_ignore_table[];
349 static const struct input_transition input_state_osc_string_table[];
350 static const struct input_transition input_state_apc_string_table[];
351 static const struct input_transition input_state_rename_string_table[];
352 static const struct input_transition input_state_consume_st_table[];
353 
354 /* ground state definition. */
355 static const struct input_state input_state_ground = {
356 	"ground",
357 	input_ground, NULL,
358 	input_state_ground_table
359 };
360 
361 /* esc_enter state definition. */
362 static const struct input_state input_state_esc_enter = {
363 	"esc_enter",
364 	input_clear, NULL,
365 	input_state_esc_enter_table
366 };
367 
368 /* esc_intermediate state definition. */
369 static const struct input_state input_state_esc_intermediate = {
370 	"esc_intermediate",
371 	NULL, NULL,
372 	input_state_esc_intermediate_table
373 };
374 
375 /* csi_enter state definition. */
376 static const struct input_state input_state_csi_enter = {
377 	"csi_enter",
378 	input_clear, NULL,
379 	input_state_csi_enter_table
380 };
381 
382 /* csi_parameter state definition. */
383 static const struct input_state input_state_csi_parameter = {
384 	"csi_parameter",
385 	NULL, NULL,
386 	input_state_csi_parameter_table
387 };
388 
389 /* csi_intermediate state definition. */
390 static const struct input_state input_state_csi_intermediate = {
391 	"csi_intermediate",
392 	NULL, NULL,
393 	input_state_csi_intermediate_table
394 };
395 
396 /* csi_ignore state definition. */
397 static const struct input_state input_state_csi_ignore = {
398 	"csi_ignore",
399 	NULL, NULL,
400 	input_state_csi_ignore_table
401 };
402 
403 /* dcs_enter state definition. */
404 static const struct input_state input_state_dcs_enter = {
405 	"dcs_enter",
406 	input_enter_dcs, NULL,
407 	input_state_dcs_enter_table
408 };
409 
410 /* dcs_parameter state definition. */
411 static const struct input_state input_state_dcs_parameter = {
412 	"dcs_parameter",
413 	NULL, NULL,
414 	input_state_dcs_parameter_table
415 };
416 
417 /* dcs_intermediate state definition. */
418 static const struct input_state input_state_dcs_intermediate = {
419 	"dcs_intermediate",
420 	NULL, NULL,
421 	input_state_dcs_intermediate_table
422 };
423 
424 /* dcs_handler state definition. */
425 static const struct input_state input_state_dcs_handler = {
426 	"dcs_handler",
427 	NULL, NULL,
428 	input_state_dcs_handler_table
429 };
430 
431 /* dcs_escape state definition. */
432 static const struct input_state input_state_dcs_escape = {
433 	"dcs_escape",
434 	NULL, NULL,
435 	input_state_dcs_escape_table
436 };
437 
438 /* dcs_ignore state definition. */
439 static const struct input_state input_state_dcs_ignore = {
440 	"dcs_ignore",
441 	NULL, NULL,
442 	input_state_dcs_ignore_table
443 };
444 
445 /* osc_string state definition. */
446 static const struct input_state input_state_osc_string = {
447 	"osc_string",
448 	input_enter_osc, input_exit_osc,
449 	input_state_osc_string_table
450 };
451 
452 /* apc_string state definition. */
453 static const struct input_state input_state_apc_string = {
454 	"apc_string",
455 	input_enter_apc, input_exit_apc,
456 	input_state_apc_string_table
457 };
458 
459 /* rename_string state definition. */
460 static const struct input_state input_state_rename_string = {
461 	"rename_string",
462 	input_enter_rename, input_exit_rename,
463 	input_state_rename_string_table
464 };
465 
466 /* consume_st state definition. */
467 static const struct input_state input_state_consume_st = {
468 	"consume_st",
469 	input_enter_rename, NULL, /* rename also waits for ST */
470 	input_state_consume_st_table
471 };
472 
473 /* ground state table. */
474 static const struct input_transition input_state_ground_table[] = {
475 	INPUT_STATE_ANYWHERE,
476 
477 	{ 0x00, 0x17, input_c0_dispatch, NULL },
478 	{ 0x19, 0x19, input_c0_dispatch, NULL },
479 	{ 0x1c, 0x1f, input_c0_dispatch, NULL },
480 	{ 0x20, 0x7e, input_print,	 NULL },
481 	{ 0x7f, 0x7f, NULL,		 NULL },
482 	{ 0x80, 0xff, input_top_bit_set, NULL },
483 
484 	{ -1, -1, NULL, NULL }
485 };
486 
487 /* esc_enter state table. */
488 static const struct input_transition input_state_esc_enter_table[] = {
489 	INPUT_STATE_ANYWHERE,
490 
491 	{ 0x00, 0x17, input_c0_dispatch,  NULL },
492 	{ 0x19, 0x19, input_c0_dispatch,  NULL },
493 	{ 0x1c, 0x1f, input_c0_dispatch,  NULL },
494 	{ 0x20, 0x2f, input_intermediate, &input_state_esc_intermediate },
495 	{ 0x30, 0x4f, input_esc_dispatch, &input_state_ground },
496 	{ 0x50, 0x50, NULL,		  &input_state_dcs_enter },
497 	{ 0x51, 0x57, input_esc_dispatch, &input_state_ground },
498 	{ 0x58, 0x58, NULL,		  &input_state_consume_st },
499 	{ 0x59, 0x59, input_esc_dispatch, &input_state_ground },
500 	{ 0x5a, 0x5a, input_esc_dispatch, &input_state_ground },
501 	{ 0x5b, 0x5b, NULL,		  &input_state_csi_enter },
502 	{ 0x5c, 0x5c, input_esc_dispatch, &input_state_ground },
503 	{ 0x5d, 0x5d, NULL,		  &input_state_osc_string },
504 	{ 0x5e, 0x5e, NULL,		  &input_state_consume_st },
505 	{ 0x5f, 0x5f, NULL,		  &input_state_apc_string },
506 	{ 0x60, 0x6a, input_esc_dispatch, &input_state_ground },
507 	{ 0x6b, 0x6b, NULL,		  &input_state_rename_string },
508 	{ 0x6c, 0x7e, input_esc_dispatch, &input_state_ground },
509 	{ 0x7f, 0xff, NULL,		  NULL },
510 
511 	{ -1, -1, NULL, NULL }
512 };
513 
514 /* esc_intermediate state table. */
515 static const struct input_transition input_state_esc_intermediate_table[] = {
516 	INPUT_STATE_ANYWHERE,
517 
518 	{ 0x00, 0x17, input_c0_dispatch,  NULL },
519 	{ 0x19, 0x19, input_c0_dispatch,  NULL },
520 	{ 0x1c, 0x1f, input_c0_dispatch,  NULL },
521 	{ 0x20, 0x2f, input_intermediate, NULL },
522 	{ 0x30, 0x7e, input_esc_dispatch, &input_state_ground },
523 	{ 0x7f, 0xff, NULL,		  NULL },
524 
525 	{ -1, -1, NULL, NULL }
526 };
527 
528 /* csi_enter state table. */
529 static const struct input_transition input_state_csi_enter_table[] = {
530 	INPUT_STATE_ANYWHERE,
531 
532 	{ 0x00, 0x17, input_c0_dispatch,  NULL },
533 	{ 0x19, 0x19, input_c0_dispatch,  NULL },
534 	{ 0x1c, 0x1f, input_c0_dispatch,  NULL },
535 	{ 0x20, 0x2f, input_intermediate, &input_state_csi_intermediate },
536 	{ 0x30, 0x39, input_parameter,	  &input_state_csi_parameter },
537 	{ 0x3a, 0x3a, input_parameter,	  &input_state_csi_parameter },
538 	{ 0x3b, 0x3b, input_parameter,	  &input_state_csi_parameter },
539 	{ 0x3c, 0x3f, input_intermediate, &input_state_csi_parameter },
540 	{ 0x40, 0x7e, input_csi_dispatch, &input_state_ground },
541 	{ 0x7f, 0xff, NULL,		  NULL },
542 
543 	{ -1, -1, NULL, NULL }
544 };
545 
546 /* csi_parameter state table. */
547 static const struct input_transition input_state_csi_parameter_table[] = {
548 	INPUT_STATE_ANYWHERE,
549 
550 	{ 0x00, 0x17, input_c0_dispatch,  NULL },
551 	{ 0x19, 0x19, input_c0_dispatch,  NULL },
552 	{ 0x1c, 0x1f, input_c0_dispatch,  NULL },
553 	{ 0x20, 0x2f, input_intermediate, &input_state_csi_intermediate },
554 	{ 0x30, 0x39, input_parameter,	  NULL },
555 	{ 0x3a, 0x3a, input_parameter,	  NULL },
556 	{ 0x3b, 0x3b, input_parameter,	  NULL },
557 	{ 0x3c, 0x3f, NULL,		  &input_state_csi_ignore },
558 	{ 0x40, 0x7e, input_csi_dispatch, &input_state_ground },
559 	{ 0x7f, 0xff, NULL,		  NULL },
560 
561 	{ -1, -1, NULL, NULL }
562 };
563 
564 /* csi_intermediate state table. */
565 static const struct input_transition input_state_csi_intermediate_table[] = {
566 	INPUT_STATE_ANYWHERE,
567 
568 	{ 0x00, 0x17, input_c0_dispatch,  NULL },
569 	{ 0x19, 0x19, input_c0_dispatch,  NULL },
570 	{ 0x1c, 0x1f, input_c0_dispatch,  NULL },
571 	{ 0x20, 0x2f, input_intermediate, NULL },
572 	{ 0x30, 0x3f, NULL,		  &input_state_csi_ignore },
573 	{ 0x40, 0x7e, input_csi_dispatch, &input_state_ground },
574 	{ 0x7f, 0xff, NULL,		  NULL },
575 
576 	{ -1, -1, NULL, NULL }
577 };
578 
579 /* csi_ignore state table. */
580 static const struct input_transition input_state_csi_ignore_table[] = {
581 	INPUT_STATE_ANYWHERE,
582 
583 	{ 0x00, 0x17, input_c0_dispatch, NULL },
584 	{ 0x19, 0x19, input_c0_dispatch, NULL },
585 	{ 0x1c, 0x1f, input_c0_dispatch, NULL },
586 	{ 0x20, 0x3f, NULL,		 NULL },
587 	{ 0x40, 0x7e, NULL,		 &input_state_ground },
588 	{ 0x7f, 0xff, NULL,		 NULL },
589 
590 	{ -1, -1, NULL, NULL }
591 };
592 
593 /* dcs_enter state table. */
594 static const struct input_transition input_state_dcs_enter_table[] = {
595 	INPUT_STATE_ANYWHERE,
596 
597 	{ 0x00, 0x17, NULL,		  NULL },
598 	{ 0x19, 0x19, NULL,		  NULL },
599 	{ 0x1c, 0x1f, NULL,		  NULL },
600 	{ 0x20, 0x2f, input_intermediate, &input_state_dcs_intermediate },
601 	{ 0x30, 0x39, input_parameter,	  &input_state_dcs_parameter },
602 	{ 0x3a, 0x3a, NULL,		  &input_state_dcs_ignore },
603 	{ 0x3b, 0x3b, input_parameter,	  &input_state_dcs_parameter },
604 	{ 0x3c, 0x3f, input_intermediate, &input_state_dcs_parameter },
605 	{ 0x40, 0x7e, input_input,	  &input_state_dcs_handler },
606 	{ 0x7f, 0xff, NULL,		  NULL },
607 
608 	{ -1, -1, NULL, NULL }
609 };
610 
611 /* dcs_parameter state table. */
612 static const struct input_transition input_state_dcs_parameter_table[] = {
613 	INPUT_STATE_ANYWHERE,
614 
615 	{ 0x00, 0x17, NULL,		  NULL },
616 	{ 0x19, 0x19, NULL,		  NULL },
617 	{ 0x1c, 0x1f, NULL,		  NULL },
618 	{ 0x20, 0x2f, input_intermediate, &input_state_dcs_intermediate },
619 	{ 0x30, 0x39, input_parameter,	  NULL },
620 	{ 0x3a, 0x3a, NULL,		  &input_state_dcs_ignore },
621 	{ 0x3b, 0x3b, input_parameter,	  NULL },
622 	{ 0x3c, 0x3f, NULL,		  &input_state_dcs_ignore },
623 	{ 0x40, 0x7e, input_input,	  &input_state_dcs_handler },
624 	{ 0x7f, 0xff, NULL,		  NULL },
625 
626 	{ -1, -1, NULL, NULL }
627 };
628 
629 /* dcs_intermediate state table. */
630 static const struct input_transition input_state_dcs_intermediate_table[] = {
631 	INPUT_STATE_ANYWHERE,
632 
633 	{ 0x00, 0x17, NULL,		  NULL },
634 	{ 0x19, 0x19, NULL,		  NULL },
635 	{ 0x1c, 0x1f, NULL,		  NULL },
636 	{ 0x20, 0x2f, input_intermediate, NULL },
637 	{ 0x30, 0x3f, NULL,		  &input_state_dcs_ignore },
638 	{ 0x40, 0x7e, input_input,	  &input_state_dcs_handler },
639 	{ 0x7f, 0xff, NULL,		  NULL },
640 
641 	{ -1, -1, NULL, NULL }
642 };
643 
644 /* dcs_handler state table. */
645 static const struct input_transition input_state_dcs_handler_table[] = {
646 	/* No INPUT_STATE_ANYWHERE */
647 
648 	{ 0x00, 0x1a, input_input,  NULL },
649 	{ 0x1b, 0x1b, NULL,	    &input_state_dcs_escape },
650 	{ 0x1c, 0xff, input_input,  NULL },
651 
652 	{ -1, -1, NULL, NULL }
653 };
654 
655 /* dcs_escape state table. */
656 static const struct input_transition input_state_dcs_escape_table[] = {
657 	/* No INPUT_STATE_ANYWHERE */
658 
659 	{ 0x00, 0x5b, input_input,	  &input_state_dcs_handler },
660 	{ 0x5c, 0x5c, input_dcs_dispatch, &input_state_ground },
661 	{ 0x5d, 0xff, input_input,	  &input_state_dcs_handler },
662 
663 	{ -1, -1, NULL, NULL }
664 };
665 
666 /* dcs_ignore state table. */
667 static const struct input_transition input_state_dcs_ignore_table[] = {
668 	INPUT_STATE_ANYWHERE,
669 
670 	{ 0x00, 0x17, NULL,	    NULL },
671 	{ 0x19, 0x19, NULL,	    NULL },
672 	{ 0x1c, 0x1f, NULL,	    NULL },
673 	{ 0x20, 0xff, NULL,	    NULL },
674 
675 	{ -1, -1, NULL, NULL }
676 };
677 
678 /* osc_string state table. */
679 static const struct input_transition input_state_osc_string_table[] = {
680 	INPUT_STATE_ANYWHERE,
681 
682 	{ 0x00, 0x06, NULL,	     NULL },
683 	{ 0x07, 0x07, input_end_bel, &input_state_ground },
684 	{ 0x08, 0x17, NULL,	     NULL },
685 	{ 0x19, 0x19, NULL,	     NULL },
686 	{ 0x1c, 0x1f, NULL,	     NULL },
687 	{ 0x20, 0xff, input_input,   NULL },
688 
689 	{ -1, -1, NULL, NULL }
690 };
691 
692 /* apc_string state table. */
693 static const struct input_transition input_state_apc_string_table[] = {
694 	INPUT_STATE_ANYWHERE,
695 
696 	{ 0x00, 0x17, NULL,	    NULL },
697 	{ 0x19, 0x19, NULL,	    NULL },
698 	{ 0x1c, 0x1f, NULL,	    NULL },
699 	{ 0x20, 0xff, input_input,  NULL },
700 
701 	{ -1, -1, NULL, NULL }
702 };
703 
704 /* rename_string state table. */
705 static const struct input_transition input_state_rename_string_table[] = {
706 	INPUT_STATE_ANYWHERE,
707 
708 	{ 0x00, 0x17, NULL,	    NULL },
709 	{ 0x19, 0x19, NULL,	    NULL },
710 	{ 0x1c, 0x1f, NULL,	    NULL },
711 	{ 0x20, 0xff, input_input,  NULL },
712 
713 	{ -1, -1, NULL, NULL }
714 };
715 
716 /* consume_st state table. */
717 static const struct input_transition input_state_consume_st_table[] = {
718 	INPUT_STATE_ANYWHERE,
719 
720 	{ 0x00, 0x17, NULL,	    NULL },
721 	{ 0x19, 0x19, NULL,	    NULL },
722 	{ 0x1c, 0x1f, NULL,	    NULL },
723 	{ 0x20, 0xff, NULL,	    NULL },
724 
725 	{ -1, -1, NULL, NULL }
726 };
727 
728 /* Input table compare. */
729 static int
730 input_table_compare(const void *key, const void *value)
731 {
732 	const struct input_ctx		*ictx = key;
733 	const struct input_table_entry	*entry = value;
734 
735 	if (ictx->ch != entry->ch)
736 		return (ictx->ch - entry->ch);
737 	return (strcmp(ictx->interm_buf, entry->interm));
738 }
739 
740 /*
741  * Timer - if this expires then have been waiting for a terminator for too
742  * long, so reset to ground.
743  */
744 static void
745 input_timer_callback(__unused int fd, __unused short events, void *arg)
746 {
747 	struct input_ctx	*ictx = arg;
748 
749 	log_debug("%s: %s expired" , __func__, ictx->state->name);
750 	input_reset(ictx, 0);
751 }
752 
753 /* Start the timer. */
754 static void
755 input_start_timer(struct input_ctx *ictx)
756 {
757 	struct timeval	tv = { .tv_sec = 5, .tv_usec = 0 };
758 
759 	event_del(&ictx->timer);
760 	event_add(&ictx->timer, &tv);
761 }
762 
763 /* Reset cell state to default. */
764 static void
765 input_reset_cell(struct input_ctx *ictx)
766 {
767 	memcpy(&ictx->cell.cell, &grid_default_cell, sizeof ictx->cell.cell);
768 	ictx->cell.set = 0;
769 	ictx->cell.g0set = ictx->cell.g1set = 0;
770 
771 	memcpy(&ictx->old_cell, &ictx->cell, sizeof ictx->old_cell);
772 	ictx->old_cx = 0;
773 	ictx->old_cy = 0;
774 }
775 
776 /* Save screen state. */
777 static void
778 input_save_state(struct input_ctx *ictx)
779 {
780 	struct screen_write_ctx	*sctx = &ictx->ctx;
781 	struct screen		*s = sctx->s;
782 
783 	memcpy(&ictx->old_cell, &ictx->cell, sizeof ictx->old_cell);
784 	ictx->old_cx = s->cx;
785 	ictx->old_cy = s->cy;
786 	ictx->old_mode = s->mode;
787 }
788 
789 /* Restore screen state. */
790 static void
791 input_restore_state(struct input_ctx *ictx)
792 {
793 	struct screen_write_ctx	*sctx = &ictx->ctx;
794 
795 	memcpy(&ictx->cell, &ictx->old_cell, sizeof ictx->cell);
796 	if (ictx->old_mode & MODE_ORIGIN)
797 		screen_write_mode_set(sctx, MODE_ORIGIN);
798 	else
799 		screen_write_mode_clear(sctx, MODE_ORIGIN);
800 	screen_write_cursormove(sctx, ictx->old_cx, ictx->old_cy, 0);
801 }
802 
803 /* Initialise input parser. */
804 struct input_ctx *
805 input_init(struct window_pane *wp, struct bufferevent *bev,
806     struct colour_palette *palette)
807 {
808 	struct input_ctx	*ictx;
809 
810 	ictx = xcalloc(1, sizeof *ictx);
811 	ictx->wp = wp;
812 	ictx->event = bev;
813 	ictx->palette = palette;
814 
815 	ictx->input_space = INPUT_BUF_START;
816 	ictx->input_buf = xmalloc(INPUT_BUF_START);
817 
818 	ictx->since_ground = evbuffer_new();
819 	if (ictx->since_ground == NULL)
820 		fatalx("out of memory");
821 
822 	evtimer_set(&ictx->timer, input_timer_callback, ictx);
823 
824 	input_reset(ictx, 0);
825 	return (ictx);
826 }
827 
828 /* Destroy input parser. */
829 void
830 input_free(struct input_ctx *ictx)
831 {
832 	u_int	i;
833 
834 	for (i = 0; i < ictx->param_list_len; i++) {
835 		if (ictx->param_list[i].type == INPUT_STRING)
836 			free(ictx->param_list[i].str);
837 	}
838 
839 	event_del(&ictx->timer);
840 
841 	free(ictx->input_buf);
842 	evbuffer_free(ictx->since_ground);
843 
844 	free(ictx);
845 }
846 
847 /* Reset input state and clear screen. */
848 void
849 input_reset(struct input_ctx *ictx, int clear)
850 {
851 	struct screen_write_ctx	*sctx = &ictx->ctx;
852 	struct window_pane	*wp = ictx->wp;
853 
854 	input_reset_cell(ictx);
855 
856 	if (clear && wp != NULL) {
857 		if (TAILQ_EMPTY(&wp->modes))
858 			screen_write_start_pane(sctx, wp, &wp->base);
859 		else
860 			screen_write_start(sctx, &wp->base);
861 		screen_write_reset(sctx);
862 		screen_write_stop(sctx);
863 	}
864 
865 	input_clear(ictx);
866 
867 	ictx->last = -1;
868 
869 	ictx->state = &input_state_ground;
870 	ictx->flags = 0;
871 }
872 
873 /* Return pending data. */
874 struct evbuffer *
875 input_pending(struct input_ctx *ictx)
876 {
877 	return (ictx->since_ground);
878 }
879 
880 /* Change input state. */
881 static void
882 input_set_state(struct input_ctx *ictx, const struct input_transition *itr)
883 {
884 	if (ictx->state->exit != NULL)
885 		ictx->state->exit(ictx);
886 	ictx->state = itr->state;
887 	if (ictx->state->enter != NULL)
888 		ictx->state->enter(ictx);
889 }
890 
891 /* Parse data. */
892 static void
893 input_parse(struct input_ctx *ictx, u_char *buf, size_t len)
894 {
895 	struct screen_write_ctx		*sctx = &ictx->ctx;
896 	const struct input_state	*state = NULL;
897 	const struct input_transition	*itr = NULL;
898 	size_t				 off = 0;
899 
900 	/* Parse the input. */
901 	while (off < len) {
902 		ictx->ch = buf[off++];
903 
904 		/* Find the transition. */
905 		if (ictx->state != state ||
906 		    itr == NULL ||
907 		    ictx->ch < itr->first ||
908 		    ictx->ch > itr->last) {
909 			itr = ictx->state->transitions;
910 			while (itr->first != -1 && itr->last != -1) {
911 				if (ictx->ch >= itr->first &&
912 				    ictx->ch <= itr->last)
913 					break;
914 				itr++;
915 			}
916 			if (itr->first == -1 || itr->last == -1) {
917 				/* No transition? Eh? */
918 				fatalx("no transition from state");
919 			}
920 		}
921 		state = ictx->state;
922 
923 		/*
924 		 * Any state except print stops the current collection. This is
925 		 * an optimization to avoid checking if the attributes have
926 		 * changed for every character. It will stop unnecessarily for
927 		 * sequences that don't make a terminal change, but they should
928 		 * be the minority.
929 		 */
930 		if (itr->handler != input_print)
931 			screen_write_collect_end(sctx);
932 
933 		/*
934 		 * Execute the handler, if any. Don't switch state if it
935 		 * returns non-zero.
936 		 */
937 		if (itr->handler != NULL && itr->handler(ictx) != 0)
938 			continue;
939 
940 		/* And switch state, if necessary. */
941 		if (itr->state != NULL)
942 			input_set_state(ictx, itr);
943 
944 		/* If not in ground state, save input. */
945 		if (ictx->state != &input_state_ground)
946 			evbuffer_add(ictx->since_ground, &ictx->ch, 1);
947 	}
948 }
949 
950 /* Parse input from pane. */
951 void
952 input_parse_pane(struct window_pane *wp)
953 {
954 	void	*new_data;
955 	size_t	 new_size;
956 
957 	new_data = window_pane_get_new_data(wp, &wp->offset, &new_size);
958 	input_parse_buffer(wp, new_data, new_size);
959 	window_pane_update_used_data(wp, &wp->offset, new_size);
960 }
961 
962 /* Parse given input. */
963 void
964 input_parse_buffer(struct window_pane *wp, u_char *buf, size_t len)
965 {
966 	struct input_ctx	*ictx = wp->ictx;
967 	struct screen_write_ctx	*sctx = &ictx->ctx;
968 
969 	if (len == 0)
970 		return;
971 
972 	window_update_activity(wp->window);
973 	wp->flags |= PANE_CHANGED;
974 
975 	/* Flag new input while in a mode. */
976 	if (!TAILQ_EMPTY(&wp->modes))
977 		wp->flags |= PANE_UNSEENCHANGES;
978 
979 	/* NULL wp if there is a mode set as don't want to update the tty. */
980 	if (TAILQ_EMPTY(&wp->modes))
981 		screen_write_start_pane(sctx, wp, &wp->base);
982 	else
983 		screen_write_start(sctx, &wp->base);
984 
985 	log_debug("%s: %%%u %s, %zu bytes: %.*s", __func__, wp->id,
986 	    ictx->state->name, len, (int)len, buf);
987 
988 	input_parse(ictx, buf, len);
989 	screen_write_stop(sctx);
990 }
991 
992 /* Parse given input for screen. */
993 void
994 input_parse_screen(struct input_ctx *ictx, struct screen *s,
995     screen_write_init_ctx_cb cb, void *arg, u_char *buf, size_t len)
996 {
997 	struct screen_write_ctx	*sctx = &ictx->ctx;
998 
999 	if (len == 0)
1000 		return;
1001 
1002 	screen_write_start_callback(sctx, s, cb, arg);
1003 	input_parse(ictx, buf, len);
1004 	screen_write_stop(sctx);
1005 }
1006 
1007 /* Split the parameter list (if any). */
1008 static int
1009 input_split(struct input_ctx *ictx)
1010 {
1011 	const char		*errstr;
1012 	char			*ptr, *out;
1013 	struct input_param	*ip;
1014 	u_int			 i;
1015 
1016 	for (i = 0; i < ictx->param_list_len; i++) {
1017 		if (ictx->param_list[i].type == INPUT_STRING)
1018 			free(ictx->param_list[i].str);
1019 	}
1020 	ictx->param_list_len = 0;
1021 
1022 	if (ictx->param_len == 0)
1023 		return (0);
1024 	ip = &ictx->param_list[0];
1025 
1026 	ptr = ictx->param_buf;
1027 	while ((out = strsep(&ptr, ";")) != NULL) {
1028 		if (*out == '\0')
1029 			ip->type = INPUT_MISSING;
1030 		else {
1031 			if (strchr(out, ':') != NULL) {
1032 				ip->type = INPUT_STRING;
1033 				ip->str = xstrdup(out);
1034 			} else {
1035 				ip->type = INPUT_NUMBER;
1036 				ip->num = strtonum(out, 0, INT_MAX, &errstr);
1037 				if (errstr != NULL)
1038 					return (-1);
1039 			}
1040 		}
1041 		ip = &ictx->param_list[++ictx->param_list_len];
1042 		if (ictx->param_list_len == nitems(ictx->param_list))
1043 			return (-1);
1044 	}
1045 
1046 	for (i = 0; i < ictx->param_list_len; i++) {
1047 		ip = &ictx->param_list[i];
1048 		if (ip->type == INPUT_MISSING)
1049 			log_debug("parameter %u: missing", i);
1050 		else if (ip->type == INPUT_STRING)
1051 			log_debug("parameter %u: string %s", i, ip->str);
1052 		else if (ip->type == INPUT_NUMBER)
1053 			log_debug("parameter %u: number %d", i, ip->num);
1054 	}
1055 
1056 	return (0);
1057 }
1058 
1059 /* Get an argument or return default value. */
1060 static int
1061 input_get(struct input_ctx *ictx, u_int validx, int minval, int defval)
1062 {
1063 	struct input_param	*ip;
1064 	int			 retval;
1065 
1066 	if (validx >= ictx->param_list_len)
1067 	    return (defval);
1068 	ip = &ictx->param_list[validx];
1069 	if (ip->type == INPUT_MISSING)
1070 		return (defval);
1071 	if (ip->type == INPUT_STRING)
1072 		return (-1);
1073 	retval = ip->num;
1074 	if (retval < minval)
1075 		return (minval);
1076 	return (retval);
1077 }
1078 
1079 /* Reply to terminal query. */
1080 static void
1081 input_reply(struct input_ctx *ictx, const char *fmt, ...)
1082 {
1083 	struct bufferevent	*bev = ictx->event;
1084 	va_list			 ap;
1085 	char			*reply;
1086 
1087 	if (bev == NULL)
1088 		return;
1089 
1090 	va_start(ap, fmt);
1091 	xvasprintf(&reply, fmt, ap);
1092 	va_end(ap);
1093 
1094 	log_debug("%s: %s", __func__, reply);
1095 	bufferevent_write(bev, reply, strlen(reply));
1096 	free(reply);
1097 }
1098 
1099 /* Clear saved state. */
1100 static void
1101 input_clear(struct input_ctx *ictx)
1102 {
1103 	event_del(&ictx->timer);
1104 
1105 	*ictx->interm_buf = '\0';
1106 	ictx->interm_len = 0;
1107 
1108 	*ictx->param_buf = '\0';
1109 	ictx->param_len = 0;
1110 
1111 	*ictx->input_buf = '\0';
1112 	ictx->input_len = 0;
1113 
1114 	ictx->input_end = INPUT_END_ST;
1115 
1116 	ictx->flags &= ~INPUT_DISCARD;
1117 }
1118 
1119 /* Reset for ground state. */
1120 static void
1121 input_ground(struct input_ctx *ictx)
1122 {
1123 	event_del(&ictx->timer);
1124 	evbuffer_drain(ictx->since_ground, EVBUFFER_LENGTH(ictx->since_ground));
1125 
1126 	if (ictx->input_space > INPUT_BUF_START) {
1127 		ictx->input_space = INPUT_BUF_START;
1128 		ictx->input_buf = xrealloc(ictx->input_buf, INPUT_BUF_START);
1129 	}
1130 }
1131 
1132 /* Output this character to the screen. */
1133 static int
1134 input_print(struct input_ctx *ictx)
1135 {
1136 	struct screen_write_ctx	*sctx = &ictx->ctx;
1137 	int			 set;
1138 
1139 	ictx->utf8started = 0; /* can't be valid UTF-8 */
1140 
1141 	set = ictx->cell.set == 0 ? ictx->cell.g0set : ictx->cell.g1set;
1142 	if (set == 1)
1143 		ictx->cell.cell.attr |= GRID_ATTR_CHARSET;
1144 	else
1145 		ictx->cell.cell.attr &= ~GRID_ATTR_CHARSET;
1146 
1147 	utf8_set(&ictx->cell.cell.data, ictx->ch);
1148 	screen_write_collect_add(sctx, &ictx->cell.cell);
1149 	ictx->last = ictx->ch;
1150 
1151 	ictx->cell.cell.attr &= ~GRID_ATTR_CHARSET;
1152 
1153 	return (0);
1154 }
1155 
1156 /* Collect intermediate string. */
1157 static int
1158 input_intermediate(struct input_ctx *ictx)
1159 {
1160 	if (ictx->interm_len == (sizeof ictx->interm_buf) - 1)
1161 		ictx->flags |= INPUT_DISCARD;
1162 	else {
1163 		ictx->interm_buf[ictx->interm_len++] = ictx->ch;
1164 		ictx->interm_buf[ictx->interm_len] = '\0';
1165 	}
1166 
1167 	return (0);
1168 }
1169 
1170 /* Collect parameter string. */
1171 static int
1172 input_parameter(struct input_ctx *ictx)
1173 {
1174 	if (ictx->param_len == (sizeof ictx->param_buf) - 1)
1175 		ictx->flags |= INPUT_DISCARD;
1176 	else {
1177 		ictx->param_buf[ictx->param_len++] = ictx->ch;
1178 		ictx->param_buf[ictx->param_len] = '\0';
1179 	}
1180 
1181 	return (0);
1182 }
1183 
1184 /* Collect input string. */
1185 static int
1186 input_input(struct input_ctx *ictx)
1187 {
1188 	size_t available;
1189 
1190 	available = ictx->input_space;
1191 	while (ictx->input_len + 1 >= available) {
1192 		available *= 2;
1193 		if (available > INPUT_BUF_LIMIT) {
1194 			ictx->flags |= INPUT_DISCARD;
1195 			return (0);
1196 		}
1197 		ictx->input_buf = xrealloc(ictx->input_buf, available);
1198 		ictx->input_space = available;
1199 	}
1200 	ictx->input_buf[ictx->input_len++] = ictx->ch;
1201 	ictx->input_buf[ictx->input_len] = '\0';
1202 
1203 	return (0);
1204 }
1205 
1206 /* Execute C0 control sequence. */
1207 static int
1208 input_c0_dispatch(struct input_ctx *ictx)
1209 {
1210 	struct screen_write_ctx	*sctx = &ictx->ctx;
1211 	struct window_pane	*wp = ictx->wp;
1212 	struct screen		*s = sctx->s;
1213 
1214 	ictx->utf8started = 0; /* can't be valid UTF-8 */
1215 
1216 	log_debug("%s: '%c'", __func__, ictx->ch);
1217 
1218 	switch (ictx->ch) {
1219 	case '\000':	/* NUL */
1220 		break;
1221 	case '\007':	/* BEL */
1222 		if (wp != NULL)
1223 			alerts_queue(wp->window, WINDOW_BELL);
1224 		break;
1225 	case '\010':	/* BS */
1226 		screen_write_backspace(sctx);
1227 		break;
1228 	case '\011':	/* HT */
1229 		/* Don't tab beyond the end of the line. */
1230 		if (s->cx >= screen_size_x(s) - 1)
1231 			break;
1232 
1233 		/* Find the next tab point, or use the last column if none. */
1234 		do {
1235 			s->cx++;
1236 			if (bit_test(s->tabs, s->cx))
1237 				break;
1238 		} while (s->cx < screen_size_x(s) - 1);
1239 		break;
1240 	case '\012':	/* LF */
1241 	case '\013':	/* VT */
1242 	case '\014':	/* FF */
1243 		screen_write_linefeed(sctx, 0, ictx->cell.cell.bg);
1244 		if (s->mode & MODE_CRLF)
1245 			screen_write_carriagereturn(sctx);
1246 		break;
1247 	case '\015':	/* CR */
1248 		screen_write_carriagereturn(sctx);
1249 		break;
1250 	case '\016':	/* SO */
1251 		ictx->cell.set = 1;
1252 		break;
1253 	case '\017':	/* SI */
1254 		ictx->cell.set = 0;
1255 		break;
1256 	default:
1257 		log_debug("%s: unknown '%c'", __func__, ictx->ch);
1258 		break;
1259 	}
1260 
1261 	ictx->last = -1;
1262 	return (0);
1263 }
1264 
1265 /* Execute escape sequence. */
1266 static int
1267 input_esc_dispatch(struct input_ctx *ictx)
1268 {
1269 	struct screen_write_ctx		*sctx = &ictx->ctx;
1270 	struct screen			*s = sctx->s;
1271 	struct input_table_entry	*entry;
1272 
1273 	if (ictx->flags & INPUT_DISCARD)
1274 		return (0);
1275 	log_debug("%s: '%c', %s", __func__, ictx->ch, ictx->interm_buf);
1276 
1277 	entry = bsearch(ictx, input_esc_table, nitems(input_esc_table),
1278 	    sizeof input_esc_table[0], input_table_compare);
1279 	if (entry == NULL) {
1280 		log_debug("%s: unknown '%c'", __func__, ictx->ch);
1281 		return (0);
1282 	}
1283 
1284 	switch (entry->type) {
1285 	case INPUT_ESC_RIS:
1286 		colour_palette_clear(ictx->palette);
1287 		input_reset_cell(ictx);
1288 		screen_write_reset(sctx);
1289 		screen_write_fullredraw(sctx);
1290 		break;
1291 	case INPUT_ESC_IND:
1292 		screen_write_linefeed(sctx, 0, ictx->cell.cell.bg);
1293 		break;
1294 	case INPUT_ESC_NEL:
1295 		screen_write_carriagereturn(sctx);
1296 		screen_write_linefeed(sctx, 0, ictx->cell.cell.bg);
1297 		break;
1298 	case INPUT_ESC_HTS:
1299 		if (s->cx < screen_size_x(s))
1300 			bit_set(s->tabs, s->cx);
1301 		break;
1302 	case INPUT_ESC_RI:
1303 		screen_write_reverseindex(sctx, ictx->cell.cell.bg);
1304 		break;
1305 	case INPUT_ESC_DECKPAM:
1306 		screen_write_mode_set(sctx, MODE_KKEYPAD);
1307 		break;
1308 	case INPUT_ESC_DECKPNM:
1309 		screen_write_mode_clear(sctx, MODE_KKEYPAD);
1310 		break;
1311 	case INPUT_ESC_DECSC:
1312 		input_save_state(ictx);
1313 		break;
1314 	case INPUT_ESC_DECRC:
1315 		input_restore_state(ictx);
1316 		break;
1317 	case INPUT_ESC_DECALN:
1318 		screen_write_alignmenttest(sctx);
1319 		break;
1320 	case INPUT_ESC_SCSG0_ON:
1321 		ictx->cell.g0set = 1;
1322 		break;
1323 	case INPUT_ESC_SCSG0_OFF:
1324 		ictx->cell.g0set = 0;
1325 		break;
1326 	case INPUT_ESC_SCSG1_ON:
1327 		ictx->cell.g1set = 1;
1328 		break;
1329 	case INPUT_ESC_SCSG1_OFF:
1330 		ictx->cell.g1set = 0;
1331 		break;
1332 	case INPUT_ESC_ST:
1333 		/* ST terminates OSC but the state transition already did it. */
1334 		break;
1335 	}
1336 
1337 	ictx->last = -1;
1338 	return (0);
1339 }
1340 
1341 /* Execute control sequence. */
1342 static int
1343 input_csi_dispatch(struct input_ctx *ictx)
1344 {
1345 	struct screen_write_ctx	       *sctx = &ictx->ctx;
1346 	struct screen		       *s = sctx->s;
1347 	struct input_table_entry       *entry;
1348 	int				i, n, m;
1349 	u_int				cx, bg = ictx->cell.cell.bg;
1350 
1351 	if (ictx->flags & INPUT_DISCARD)
1352 		return (0);
1353 
1354 	log_debug("%s: '%c' \"%s\" \"%s\"", __func__, ictx->ch,
1355 	    ictx->interm_buf, ictx->param_buf);
1356 
1357 	if (input_split(ictx) != 0)
1358 		return (0);
1359 
1360 	entry = bsearch(ictx, input_csi_table, nitems(input_csi_table),
1361 	    sizeof input_csi_table[0], input_table_compare);
1362 	if (entry == NULL) {
1363 		log_debug("%s: unknown '%c'", __func__, ictx->ch);
1364 		return (0);
1365 	}
1366 
1367 	switch (entry->type) {
1368 	case INPUT_CSI_CBT:
1369 		/* Find the previous tab point, n times. */
1370 		cx = s->cx;
1371 		if (cx > screen_size_x(s) - 1)
1372 			cx = screen_size_x(s) - 1;
1373 		n = input_get(ictx, 0, 1, 1);
1374 		if (n == -1)
1375 			break;
1376 		while (cx > 0 && n-- > 0) {
1377 			do
1378 				cx--;
1379 			while (cx > 0 && !bit_test(s->tabs, cx));
1380 		}
1381 		s->cx = cx;
1382 		break;
1383 	case INPUT_CSI_CUB:
1384 		n = input_get(ictx, 0, 1, 1);
1385 		if (n != -1)
1386 			screen_write_cursorleft(sctx, n);
1387 		break;
1388 	case INPUT_CSI_CUD:
1389 		n = input_get(ictx, 0, 1, 1);
1390 		if (n != -1)
1391 			screen_write_cursordown(sctx, n);
1392 		break;
1393 	case INPUT_CSI_CUF:
1394 		n = input_get(ictx, 0, 1, 1);
1395 		if (n != -1)
1396 			screen_write_cursorright(sctx, n);
1397 		break;
1398 	case INPUT_CSI_CUP:
1399 		n = input_get(ictx, 0, 1, 1);
1400 		m = input_get(ictx, 1, 1, 1);
1401 		if (n != -1 && m != -1)
1402 			screen_write_cursormove(sctx, m - 1, n - 1, 1);
1403 		break;
1404 	case INPUT_CSI_MODSET:
1405 		n = input_get(ictx, 0, 0, 0);
1406 		m = input_get(ictx, 1, 0, 0);
1407 		if (options_get_number(global_options, "extended-keys") == 2)
1408 			break;
1409 		if (n == 0 || (n == 4 && m == 0))
1410 			screen_write_mode_clear(sctx, MODE_KEXTENDED);
1411 		else if (n == 4 && (m == 1 || m == 2))
1412 			screen_write_mode_set(sctx, MODE_KEXTENDED);
1413 		break;
1414 	case INPUT_CSI_MODOFF:
1415 		n = input_get(ictx, 0, 0, 0);
1416 		if (n == 4)
1417 			screen_write_mode_clear(sctx, MODE_KEXTENDED);
1418 		break;
1419 	case INPUT_CSI_WINOPS:
1420 		input_csi_dispatch_winops(ictx);
1421 		break;
1422 	case INPUT_CSI_CUU:
1423 		n = input_get(ictx, 0, 1, 1);
1424 		if (n != -1)
1425 			screen_write_cursorup(sctx, n);
1426 		break;
1427 	case INPUT_CSI_CNL:
1428 		n = input_get(ictx, 0, 1, 1);
1429 		if (n != -1) {
1430 			screen_write_carriagereturn(sctx);
1431 			screen_write_cursordown(sctx, n);
1432 		}
1433 		break;
1434 	case INPUT_CSI_CPL:
1435 		n = input_get(ictx, 0, 1, 1);
1436 		if (n != -1) {
1437 			screen_write_carriagereturn(sctx);
1438 			screen_write_cursorup(sctx, n);
1439 		}
1440 		break;
1441 	case INPUT_CSI_DA:
1442 		switch (input_get(ictx, 0, 0, 0)) {
1443 		case -1:
1444 			break;
1445 		case 0:
1446 			input_reply(ictx, "\033[?1;2c");
1447 			break;
1448 		default:
1449 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1450 			break;
1451 		}
1452 		break;
1453 	case INPUT_CSI_DA_TWO:
1454 		switch (input_get(ictx, 0, 0, 0)) {
1455 		case -1:
1456 			break;
1457 		case 0:
1458 			input_reply(ictx, "\033[>84;0;0c");
1459 			break;
1460 		default:
1461 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1462 			break;
1463 		}
1464 		break;
1465 	case INPUT_CSI_ECH:
1466 		n = input_get(ictx, 0, 1, 1);
1467 		if (n != -1)
1468 			screen_write_clearcharacter(sctx, n, bg);
1469 		break;
1470 	case INPUT_CSI_DCH:
1471 		n = input_get(ictx, 0, 1, 1);
1472 		if (n != -1)
1473 			screen_write_deletecharacter(sctx, n, bg);
1474 		break;
1475 	case INPUT_CSI_DECSTBM:
1476 		n = input_get(ictx, 0, 1, 1);
1477 		m = input_get(ictx, 1, 1, screen_size_y(s));
1478 		if (n != -1 && m != -1)
1479 			screen_write_scrollregion(sctx, n - 1, m - 1);
1480 		break;
1481 	case INPUT_CSI_DL:
1482 		n = input_get(ictx, 0, 1, 1);
1483 		if (n != -1)
1484 			screen_write_deleteline(sctx, n, bg);
1485 		break;
1486 	case INPUT_CSI_DSR:
1487 		switch (input_get(ictx, 0, 0, 0)) {
1488 		case -1:
1489 			break;
1490 		case 5:
1491 			input_reply(ictx, "\033[0n");
1492 			break;
1493 		case 6:
1494 			input_reply(ictx, "\033[%u;%uR", s->cy + 1, s->cx + 1);
1495 			break;
1496 		default:
1497 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1498 			break;
1499 		}
1500 		break;
1501 	case INPUT_CSI_ED:
1502 		switch (input_get(ictx, 0, 0, 0)) {
1503 		case -1:
1504 			break;
1505 		case 0:
1506 			screen_write_clearendofscreen(sctx, bg);
1507 			break;
1508 		case 1:
1509 			screen_write_clearstartofscreen(sctx, bg);
1510 			break;
1511 		case 2:
1512 			screen_write_clearscreen(sctx, bg);
1513 			break;
1514 		case 3:
1515 			if (input_get(ictx, 1, 0, 0) == 0) {
1516 				/*
1517 				 * Linux console extension to clear history
1518 				 * (for example before locking the screen).
1519 				 */
1520 				screen_write_clearhistory(sctx);
1521 			}
1522 			break;
1523 		default:
1524 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1525 			break;
1526 		}
1527 		break;
1528 	case INPUT_CSI_EL:
1529 		switch (input_get(ictx, 0, 0, 0)) {
1530 		case -1:
1531 			break;
1532 		case 0:
1533 			screen_write_clearendofline(sctx, bg);
1534 			break;
1535 		case 1:
1536 			screen_write_clearstartofline(sctx, bg);
1537 			break;
1538 		case 2:
1539 			screen_write_clearline(sctx, bg);
1540 			break;
1541 		default:
1542 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1543 			break;
1544 		}
1545 		break;
1546 	case INPUT_CSI_HPA:
1547 		n = input_get(ictx, 0, 1, 1);
1548 		if (n != -1)
1549 			screen_write_cursormove(sctx, n - 1, -1, 1);
1550 		break;
1551 	case INPUT_CSI_ICH:
1552 		n = input_get(ictx, 0, 1, 1);
1553 		if (n != -1)
1554 			screen_write_insertcharacter(sctx, n, bg);
1555 		break;
1556 	case INPUT_CSI_IL:
1557 		n = input_get(ictx, 0, 1, 1);
1558 		if (n != -1)
1559 			screen_write_insertline(sctx, n, bg);
1560 		break;
1561 	case INPUT_CSI_REP:
1562 		n = input_get(ictx, 0, 1, 1);
1563 		if (n == -1)
1564 			break;
1565 
1566 		m = screen_size_x(s) - s->cx;
1567 		if (n > m)
1568 			n = m;
1569 
1570 		if (ictx->last == -1)
1571 			break;
1572 		ictx->ch = ictx->last;
1573 
1574 		for (i = 0; i < n; i++)
1575 			input_print(ictx);
1576 		break;
1577 	case INPUT_CSI_RCP:
1578 		input_restore_state(ictx);
1579 		break;
1580 	case INPUT_CSI_RM:
1581 		input_csi_dispatch_rm(ictx);
1582 		break;
1583 	case INPUT_CSI_RM_PRIVATE:
1584 		input_csi_dispatch_rm_private(ictx);
1585 		break;
1586 	case INPUT_CSI_SCP:
1587 		input_save_state(ictx);
1588 		break;
1589 	case INPUT_CSI_SGR:
1590 		input_csi_dispatch_sgr(ictx);
1591 		break;
1592 	case INPUT_CSI_SM:
1593 		input_csi_dispatch_sm(ictx);
1594 		break;
1595 	case INPUT_CSI_SM_PRIVATE:
1596 		input_csi_dispatch_sm_private(ictx);
1597 		break;
1598 	case INPUT_CSI_SU:
1599 		n = input_get(ictx, 0, 1, 1);
1600 		if (n != -1)
1601 			screen_write_scrollup(sctx, n, bg);
1602 		break;
1603 	case INPUT_CSI_SD:
1604 		n = input_get(ictx, 0, 1, 1);
1605 		if (n != -1)
1606 			screen_write_scrolldown(sctx, n, bg);
1607 		break;
1608 	case INPUT_CSI_TBC:
1609 		switch (input_get(ictx, 0, 0, 0)) {
1610 		case -1:
1611 			break;
1612 		case 0:
1613 			if (s->cx < screen_size_x(s))
1614 				bit_clear(s->tabs, s->cx);
1615 			break;
1616 		case 3:
1617 			bit_nclear(s->tabs, 0, screen_size_x(s) - 1);
1618 			break;
1619 		default:
1620 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1621 			break;
1622 		}
1623 		break;
1624 	case INPUT_CSI_VPA:
1625 		n = input_get(ictx, 0, 1, 1);
1626 		if (n != -1)
1627 			screen_write_cursormove(sctx, -1, n - 1, 1);
1628 		break;
1629 	case INPUT_CSI_DECSCUSR:
1630 		n = input_get(ictx, 0, 0, 0);
1631 		if (n != -1)
1632 			screen_set_cursor_style(n, &s->cstyle, &s->mode);
1633 		break;
1634 	case INPUT_CSI_XDA:
1635 		n = input_get(ictx, 0, 0, 0);
1636 		if (n == 0)
1637 			input_reply(ictx, "\033P>|tmux %s\033\\", getversion());
1638 		break;
1639 
1640 	}
1641 
1642 	ictx->last = -1;
1643 	return (0);
1644 }
1645 
1646 /* Handle CSI RM. */
1647 static void
1648 input_csi_dispatch_rm(struct input_ctx *ictx)
1649 {
1650 	struct screen_write_ctx	*sctx = &ictx->ctx;
1651 	u_int			 i;
1652 
1653 	for (i = 0; i < ictx->param_list_len; i++) {
1654 		switch (input_get(ictx, i, 0, -1)) {
1655 		case -1:
1656 			break;
1657 		case 4:		/* IRM */
1658 			screen_write_mode_clear(sctx, MODE_INSERT);
1659 			break;
1660 		case 34:
1661 			screen_write_mode_set(sctx, MODE_CURSOR_VERY_VISIBLE);
1662 			break;
1663 		default:
1664 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1665 			break;
1666 		}
1667 	}
1668 }
1669 
1670 /* Handle CSI private RM. */
1671 static void
1672 input_csi_dispatch_rm_private(struct input_ctx *ictx)
1673 {
1674 	struct screen_write_ctx	*sctx = &ictx->ctx;
1675 	struct grid_cell	*gc = &ictx->cell.cell;
1676 	u_int			 i;
1677 
1678 	for (i = 0; i < ictx->param_list_len; i++) {
1679 		switch (input_get(ictx, i, 0, -1)) {
1680 		case -1:
1681 			break;
1682 		case 1:		/* DECCKM */
1683 			screen_write_mode_clear(sctx, MODE_KCURSOR);
1684 			break;
1685 		case 3:		/* DECCOLM */
1686 			screen_write_cursormove(sctx, 0, 0, 1);
1687 			screen_write_clearscreen(sctx, gc->bg);
1688 			break;
1689 		case 6:		/* DECOM */
1690 			screen_write_mode_clear(sctx, MODE_ORIGIN);
1691 			screen_write_cursormove(sctx, 0, 0, 1);
1692 			break;
1693 		case 7:		/* DECAWM */
1694 			screen_write_mode_clear(sctx, MODE_WRAP);
1695 			break;
1696 		case 12:
1697 			screen_write_mode_clear(sctx, MODE_CURSOR_BLINKING);
1698 			screen_write_mode_set(sctx, MODE_CURSOR_BLINKING_SET);
1699 			break;
1700 		case 25:	/* TCEM */
1701 			screen_write_mode_clear(sctx, MODE_CURSOR);
1702 			break;
1703 		case 1000:
1704 		case 1001:
1705 		case 1002:
1706 		case 1003:
1707 			screen_write_mode_clear(sctx, ALL_MOUSE_MODES);
1708 			break;
1709 		case 1004:
1710 			screen_write_mode_clear(sctx, MODE_FOCUSON);
1711 			break;
1712 		case 1005:
1713 			screen_write_mode_clear(sctx, MODE_MOUSE_UTF8);
1714 			break;
1715 		case 1006:
1716 			screen_write_mode_clear(sctx, MODE_MOUSE_SGR);
1717 			break;
1718 		case 47:
1719 		case 1047:
1720 			screen_write_alternateoff(sctx, gc, 0);
1721 			break;
1722 		case 1049:
1723 			screen_write_alternateoff(sctx, gc, 1);
1724 			break;
1725 		case 2004:
1726 			screen_write_mode_clear(sctx, MODE_BRACKETPASTE);
1727 			break;
1728 		default:
1729 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1730 			break;
1731 		}
1732 	}
1733 }
1734 
1735 /* Handle CSI SM. */
1736 static void
1737 input_csi_dispatch_sm(struct input_ctx *ictx)
1738 {
1739 	struct screen_write_ctx	*sctx = &ictx->ctx;
1740 	u_int			 i;
1741 
1742 	for (i = 0; i < ictx->param_list_len; i++) {
1743 		switch (input_get(ictx, i, 0, -1)) {
1744 		case -1:
1745 			break;
1746 		case 4:		/* IRM */
1747 			screen_write_mode_set(sctx, MODE_INSERT);
1748 			break;
1749 		case 34:
1750 			screen_write_mode_clear(sctx, MODE_CURSOR_VERY_VISIBLE);
1751 			break;
1752 		default:
1753 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1754 			break;
1755 		}
1756 	}
1757 }
1758 
1759 /* Handle CSI private SM. */
1760 static void
1761 input_csi_dispatch_sm_private(struct input_ctx *ictx)
1762 {
1763 	struct screen_write_ctx	*sctx = &ictx->ctx;
1764 	struct grid_cell	*gc = &ictx->cell.cell;
1765 	u_int			 i;
1766 
1767 	for (i = 0; i < ictx->param_list_len; i++) {
1768 		switch (input_get(ictx, i, 0, -1)) {
1769 		case -1:
1770 			break;
1771 		case 1:		/* DECCKM */
1772 			screen_write_mode_set(sctx, MODE_KCURSOR);
1773 			break;
1774 		case 3:		/* DECCOLM */
1775 			screen_write_cursormove(sctx, 0, 0, 1);
1776 			screen_write_clearscreen(sctx, ictx->cell.cell.bg);
1777 			break;
1778 		case 6:		/* DECOM */
1779 			screen_write_mode_set(sctx, MODE_ORIGIN);
1780 			screen_write_cursormove(sctx, 0, 0, 1);
1781 			break;
1782 		case 7:		/* DECAWM */
1783 			screen_write_mode_set(sctx, MODE_WRAP);
1784 			break;
1785 		case 12:
1786 			screen_write_mode_set(sctx, MODE_CURSOR_BLINKING);
1787 			screen_write_mode_set(sctx, MODE_CURSOR_BLINKING_SET);
1788 			break;
1789 		case 25:	/* TCEM */
1790 			screen_write_mode_set(sctx, MODE_CURSOR);
1791 			break;
1792 		case 1000:
1793 			screen_write_mode_clear(sctx, ALL_MOUSE_MODES);
1794 			screen_write_mode_set(sctx, MODE_MOUSE_STANDARD);
1795 			break;
1796 		case 1002:
1797 			screen_write_mode_clear(sctx, ALL_MOUSE_MODES);
1798 			screen_write_mode_set(sctx, MODE_MOUSE_BUTTON);
1799 			break;
1800 		case 1003:
1801 			screen_write_mode_clear(sctx, ALL_MOUSE_MODES);
1802 			screen_write_mode_set(sctx, MODE_MOUSE_ALL);
1803 			break;
1804 		case 1004:
1805 			screen_write_mode_set(sctx, MODE_FOCUSON);
1806 			break;
1807 		case 1005:
1808 			screen_write_mode_set(sctx, MODE_MOUSE_UTF8);
1809 			break;
1810 		case 1006:
1811 			screen_write_mode_set(sctx, MODE_MOUSE_SGR);
1812 			break;
1813 		case 47:
1814 		case 1047:
1815 			screen_write_alternateon(sctx, gc, 0);
1816 			break;
1817 		case 1049:
1818 			screen_write_alternateon(sctx, gc, 1);
1819 			break;
1820 		case 2004:
1821 			screen_write_mode_set(sctx, MODE_BRACKETPASTE);
1822 			break;
1823 		default:
1824 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1825 			break;
1826 		}
1827 	}
1828 }
1829 
1830 /* Handle CSI window operations. */
1831 static void
1832 input_csi_dispatch_winops(struct input_ctx *ictx)
1833 {
1834 	struct screen_write_ctx	*sctx = &ictx->ctx;
1835 	struct screen		*s = sctx->s;
1836 	struct window_pane	*wp = ictx->wp;
1837 	u_int			 x = screen_size_x(s), y = screen_size_y(s);
1838 	int			 n, m;
1839 
1840 	m = 0;
1841 	while ((n = input_get(ictx, m, 0, -1)) != -1) {
1842 		switch (n) {
1843 		case 1:
1844 		case 2:
1845 		case 5:
1846 		case 6:
1847 		case 7:
1848 		case 11:
1849 		case 13:
1850 		case 14:
1851 		case 19:
1852 		case 20:
1853 		case 21:
1854 		case 24:
1855 			break;
1856 		case 3:
1857 		case 4:
1858 		case 8:
1859 			m++;
1860 			if (input_get(ictx, m, 0, -1) == -1)
1861 				return;
1862 			/* FALLTHROUGH */
1863 		case 9:
1864 		case 10:
1865 			m++;
1866 			if (input_get(ictx, m, 0, -1) == -1)
1867 				return;
1868 			break;
1869 		case 22:
1870 			m++;
1871 			switch (input_get(ictx, m, 0, -1)) {
1872 			case -1:
1873 				return;
1874 			case 0:
1875 			case 2:
1876 				screen_push_title(sctx->s);
1877 				break;
1878 			}
1879 			break;
1880 		case 23:
1881 			m++;
1882 			switch (input_get(ictx, m, 0, -1)) {
1883 			case -1:
1884 				return;
1885 			case 0:
1886 			case 2:
1887 				screen_pop_title(sctx->s);
1888 				if (wp == NULL)
1889 					break;
1890 				notify_pane("pane-title-changed", wp);
1891 				server_redraw_window_borders(wp->window);
1892 				server_status_window(wp->window);
1893 				break;
1894 			}
1895 			break;
1896 		case 18:
1897 			input_reply(ictx, "\033[8;%u;%ut", y, x);
1898 			break;
1899 		default:
1900 			log_debug("%s: unknown '%c'", __func__, ictx->ch);
1901 			break;
1902 		}
1903 		m++;
1904 	}
1905 }
1906 
1907 /* Helper for 256 colour SGR. */
1908 static int
1909 input_csi_dispatch_sgr_256_do(struct input_ctx *ictx, int fgbg, int c)
1910 {
1911 	struct grid_cell	*gc = &ictx->cell.cell;
1912 
1913 	if (c == -1 || c > 255) {
1914 		if (fgbg == 38)
1915 			gc->fg = 8;
1916 		else if (fgbg == 48)
1917 			gc->bg = 8;
1918 	} else {
1919 		if (fgbg == 38)
1920 			gc->fg = c | COLOUR_FLAG_256;
1921 		else if (fgbg == 48)
1922 			gc->bg = c | COLOUR_FLAG_256;
1923 		else if (fgbg == 58)
1924 			gc->us = c | COLOUR_FLAG_256;
1925 	}
1926 	return (1);
1927 }
1928 
1929 /* Handle CSI SGR for 256 colours. */
1930 static void
1931 input_csi_dispatch_sgr_256(struct input_ctx *ictx, int fgbg, u_int *i)
1932 {
1933 	int	c;
1934 
1935 	c = input_get(ictx, (*i) + 1, 0, -1);
1936 	if (input_csi_dispatch_sgr_256_do(ictx, fgbg, c))
1937 		(*i)++;
1938 }
1939 
1940 /* Helper for RGB colour SGR. */
1941 static int
1942 input_csi_dispatch_sgr_rgb_do(struct input_ctx *ictx, int fgbg, int r, int g,
1943     int b)
1944 {
1945 	struct grid_cell	*gc = &ictx->cell.cell;
1946 
1947 	if (r == -1 || r > 255)
1948 		return (0);
1949 	if (g == -1 || g > 255)
1950 		return (0);
1951 	if (b == -1 || b > 255)
1952 		return (0);
1953 
1954 	if (fgbg == 38)
1955 		gc->fg = colour_join_rgb(r, g, b);
1956 	else if (fgbg == 48)
1957 		gc->bg = colour_join_rgb(r, g, b);
1958 	else if (fgbg == 58)
1959 		gc->us = colour_join_rgb(r, g, b);
1960 	return (1);
1961 }
1962 
1963 /* Handle CSI SGR for RGB colours. */
1964 static void
1965 input_csi_dispatch_sgr_rgb(struct input_ctx *ictx, int fgbg, u_int *i)
1966 {
1967 	int	r, g, b;
1968 
1969 	r = input_get(ictx, (*i) + 1, 0, -1);
1970 	g = input_get(ictx, (*i) + 2, 0, -1);
1971 	b = input_get(ictx, (*i) + 3, 0, -1);
1972 	if (input_csi_dispatch_sgr_rgb_do(ictx, fgbg, r, g, b))
1973 		(*i) += 3;
1974 }
1975 
1976 /* Handle CSI SGR with a ISO parameter. */
1977 static void
1978 input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i)
1979 {
1980 	struct grid_cell	*gc = &ictx->cell.cell;
1981 	char			*s = ictx->param_list[i].str, *copy, *ptr, *out;
1982 	int			 p[8];
1983 	u_int			 n;
1984 	const char		*errstr;
1985 
1986 	for (n = 0; n < nitems(p); n++)
1987 		p[n] = -1;
1988 	n = 0;
1989 
1990 	ptr = copy = xstrdup(s);
1991 	while ((out = strsep(&ptr, ":")) != NULL) {
1992 		if (*out != '\0') {
1993 			p[n++] = strtonum(out, 0, INT_MAX, &errstr);
1994 			if (errstr != NULL || n == nitems(p)) {
1995 				free(copy);
1996 				return;
1997 			}
1998 		} else {
1999 			n++;
2000 			if (n == nitems(p)) {
2001 				free(copy);
2002 				return;
2003 			}
2004 		}
2005 		log_debug("%s: %u = %d", __func__, n - 1, p[n - 1]);
2006 	}
2007 	free(copy);
2008 
2009 	if (n == 0)
2010 		return;
2011 	if (p[0] == 4) {
2012 		if (n != 2)
2013 			return;
2014 		switch (p[1]) {
2015 		case 0:
2016 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2017 			break;
2018 		case 1:
2019 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2020 			gc->attr |= GRID_ATTR_UNDERSCORE;
2021 			break;
2022 		case 2:
2023 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2024 			gc->attr |= GRID_ATTR_UNDERSCORE_2;
2025 			break;
2026 		case 3:
2027 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2028 			gc->attr |= GRID_ATTR_UNDERSCORE_3;
2029 			break;
2030 		case 4:
2031 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2032 			gc->attr |= GRID_ATTR_UNDERSCORE_4;
2033 			break;
2034 		case 5:
2035 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2036 			gc->attr |= GRID_ATTR_UNDERSCORE_5;
2037 			break;
2038 		}
2039 		return;
2040 	}
2041 	if (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58))
2042 		return;
2043 	switch (p[1]) {
2044 	case 2:
2045 		if (n < 3)
2046 			break;
2047 		if (n == 5)
2048 			i = 2;
2049 		else
2050 			i = 3;
2051 		if (n < i + 3)
2052 			break;
2053 		input_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1],
2054 		    p[i + 2]);
2055 		break;
2056 	case 5:
2057 		if (n < 3)
2058 			break;
2059 		input_csi_dispatch_sgr_256_do(ictx, p[0], p[2]);
2060 		break;
2061 	}
2062 }
2063 
2064 /* Handle CSI SGR. */
2065 static void
2066 input_csi_dispatch_sgr(struct input_ctx *ictx)
2067 {
2068 	struct grid_cell	*gc = &ictx->cell.cell;
2069 	u_int			 i, link;
2070 	int			 n;
2071 
2072 	if (ictx->param_list_len == 0) {
2073 		memcpy(gc, &grid_default_cell, sizeof *gc);
2074 		return;
2075 	}
2076 
2077 	for (i = 0; i < ictx->param_list_len; i++) {
2078 		if (ictx->param_list[i].type == INPUT_STRING) {
2079 			input_csi_dispatch_sgr_colon(ictx, i);
2080 			continue;
2081 		}
2082 		n = input_get(ictx, i, 0, 0);
2083 		if (n == -1)
2084 			continue;
2085 
2086 		if (n == 38 || n == 48 || n == 58) {
2087 			i++;
2088 			switch (input_get(ictx, i, 0, -1)) {
2089 			case 2:
2090 				input_csi_dispatch_sgr_rgb(ictx, n, &i);
2091 				break;
2092 			case 5:
2093 				input_csi_dispatch_sgr_256(ictx, n, &i);
2094 				break;
2095 			}
2096 			continue;
2097 		}
2098 
2099 		switch (n) {
2100 		case 0:
2101 			link = gc->link;
2102 			memcpy(gc, &grid_default_cell, sizeof *gc);
2103 			gc->link = link;
2104 			break;
2105 		case 1:
2106 			gc->attr |= GRID_ATTR_BRIGHT;
2107 			break;
2108 		case 2:
2109 			gc->attr |= GRID_ATTR_DIM;
2110 			break;
2111 		case 3:
2112 			gc->attr |= GRID_ATTR_ITALICS;
2113 			break;
2114 		case 4:
2115 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2116 			gc->attr |= GRID_ATTR_UNDERSCORE;
2117 			break;
2118 		case 5:
2119 		case 6:
2120 			gc->attr |= GRID_ATTR_BLINK;
2121 			break;
2122 		case 7:
2123 			gc->attr |= GRID_ATTR_REVERSE;
2124 			break;
2125 		case 8:
2126 			gc->attr |= GRID_ATTR_HIDDEN;
2127 			break;
2128 		case 9:
2129 			gc->attr |= GRID_ATTR_STRIKETHROUGH;
2130 			break;
2131 		case 21:
2132 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2133 			gc->attr |= GRID_ATTR_UNDERSCORE_2;
2134 			break;
2135 		case 22:
2136 			gc->attr &= ~(GRID_ATTR_BRIGHT|GRID_ATTR_DIM);
2137 			break;
2138 		case 23:
2139 			gc->attr &= ~GRID_ATTR_ITALICS;
2140 			break;
2141 		case 24:
2142 			gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
2143 			break;
2144 		case 25:
2145 			gc->attr &= ~GRID_ATTR_BLINK;
2146 			break;
2147 		case 27:
2148 			gc->attr &= ~GRID_ATTR_REVERSE;
2149 			break;
2150 		case 28:
2151 			gc->attr &= ~GRID_ATTR_HIDDEN;
2152 			break;
2153 		case 29:
2154 			gc->attr &= ~GRID_ATTR_STRIKETHROUGH;
2155 			break;
2156 		case 30:
2157 		case 31:
2158 		case 32:
2159 		case 33:
2160 		case 34:
2161 		case 35:
2162 		case 36:
2163 		case 37:
2164 			gc->fg = n - 30;
2165 			break;
2166 		case 39:
2167 			gc->fg = 8;
2168 			break;
2169 		case 40:
2170 		case 41:
2171 		case 42:
2172 		case 43:
2173 		case 44:
2174 		case 45:
2175 		case 46:
2176 		case 47:
2177 			gc->bg = n - 40;
2178 			break;
2179 		case 49:
2180 			gc->bg = 8;
2181 			break;
2182 		case 53:
2183 			gc->attr |= GRID_ATTR_OVERLINE;
2184 			break;
2185 		case 55:
2186 			gc->attr &= ~GRID_ATTR_OVERLINE;
2187 			break;
2188 		case 59:
2189 			gc->us = 8;
2190 			break;
2191 		case 90:
2192 		case 91:
2193 		case 92:
2194 		case 93:
2195 		case 94:
2196 		case 95:
2197 		case 96:
2198 		case 97:
2199 			gc->fg = n;
2200 			break;
2201 		case 100:
2202 		case 101:
2203 		case 102:
2204 		case 103:
2205 		case 104:
2206 		case 105:
2207 		case 106:
2208 		case 107:
2209 			gc->bg = n - 10;
2210 			break;
2211 		}
2212 	}
2213 }
2214 
2215 /* End of input with BEL. */
2216 static int
2217 input_end_bel(struct input_ctx *ictx)
2218 {
2219 	log_debug("%s", __func__);
2220 
2221 	ictx->input_end = INPUT_END_BEL;
2222 
2223 	return (0);
2224 }
2225 
2226 /* DCS string started. */
2227 static void
2228 input_enter_dcs(struct input_ctx *ictx)
2229 {
2230 	log_debug("%s", __func__);
2231 
2232 	input_clear(ictx);
2233 	input_start_timer(ictx);
2234 	ictx->last = -1;
2235 }
2236 
2237 /* DCS terminator (ST) received. */
2238 static int
2239 input_dcs_dispatch(struct input_ctx *ictx)
2240 {
2241 	struct window_pane	*wp = ictx->wp;
2242 	struct screen_write_ctx	*sctx = &ictx->ctx;
2243 	u_char			*buf = ictx->input_buf;
2244 	size_t			 len = ictx->input_len;
2245 	const char		 prefix[] = "tmux;";
2246 	const u_int		 prefixlen = (sizeof prefix) - 1;
2247 	long long		 allow_passthrough = 0;
2248 
2249 	if (wp == NULL)
2250 		return (0);
2251 	if (ictx->flags & INPUT_DISCARD) {
2252 		log_debug("%s: %zu bytes (discard)", __func__, len);
2253 		return (0);
2254 	}
2255 	log_debug("%s: %zu bytes", __func__, len);
2256 
2257 	allow_passthrough = options_get_number(wp->options, "allow-passthrough");
2258 	if (!allow_passthrough)
2259 		return (0);
2260 	log_debug("%s: \"%s\"", __func__, buf);
2261 
2262 	if (len >= prefixlen && strncmp(buf, prefix, prefixlen) == 0) {
2263 		screen_write_rawstring(sctx, buf + prefixlen, len - prefixlen,
2264 		    allow_passthrough == 2);
2265 	}
2266 
2267 	return (0);
2268 }
2269 
2270 /* OSC string started. */
2271 static void
2272 input_enter_osc(struct input_ctx *ictx)
2273 {
2274 	log_debug("%s", __func__);
2275 
2276 	input_clear(ictx);
2277 	input_start_timer(ictx);
2278 	ictx->last = -1;
2279 }
2280 
2281 /* OSC terminator (ST) received. */
2282 static void
2283 input_exit_osc(struct input_ctx *ictx)
2284 {
2285 	struct screen_write_ctx	*sctx = &ictx->ctx;
2286 	struct window_pane	*wp = ictx->wp;
2287 	u_char			*p = ictx->input_buf;
2288 	u_int			 option;
2289 
2290 	if (ictx->flags & INPUT_DISCARD)
2291 		return;
2292 	if (ictx->input_len < 1 || *p < '0' || *p > '9')
2293 		return;
2294 
2295 	log_debug("%s: \"%s\" (end %s)", __func__, p,
2296 	    ictx->input_end == INPUT_END_ST ? "ST" : "BEL");
2297 
2298 	option = 0;
2299 	while (*p >= '0' && *p <= '9')
2300 		option = option * 10 + *p++ - '0';
2301 	if (*p != ';' && *p != '\0')
2302 		return;
2303 	if (*p == ';')
2304 		p++;
2305 
2306 	switch (option) {
2307 	case 0:
2308 	case 2:
2309 		if (screen_set_title(sctx->s, p) && wp != NULL) {
2310 			notify_pane("pane-title-changed", wp);
2311 			server_redraw_window_borders(wp->window);
2312 			server_status_window(wp->window);
2313 		}
2314 		break;
2315 	case 4:
2316 		input_osc_4(ictx, p);
2317 		break;
2318 	case 7:
2319 		if (utf8_isvalid(p)) {
2320 			screen_set_path(sctx->s, p);
2321 			if (wp != NULL) {
2322 				server_redraw_window_borders(wp->window);
2323 				server_status_window(wp->window);
2324 			}
2325 		}
2326 		break;
2327 	case 8:
2328 		input_osc_8(ictx, p);
2329 		break;
2330 	case 10:
2331 		input_osc_10(ictx, p);
2332 		break;
2333 	case 11:
2334 		input_osc_11(ictx, p);
2335 		break;
2336 	case 12:
2337 		input_osc_12(ictx, p);
2338 		break;
2339 	case 52:
2340 		input_osc_52(ictx, p);
2341 		break;
2342 	case 104:
2343 		input_osc_104(ictx, p);
2344 		break;
2345 	case 110:
2346 		input_osc_110(ictx, p);
2347 		break;
2348 	case 111:
2349 		input_osc_111(ictx, p);
2350 		break;
2351 	case 112:
2352 		input_osc_112(ictx, p);
2353 		break;
2354 	case 133:
2355 		input_osc_133(ictx, p);
2356 		break;
2357 	default:
2358 		log_debug("%s: unknown '%u'", __func__, option);
2359 		break;
2360 	}
2361 }
2362 
2363 /* APC string started. */
2364 static void
2365 input_enter_apc(struct input_ctx *ictx)
2366 {
2367 	log_debug("%s", __func__);
2368 
2369 	input_clear(ictx);
2370 	input_start_timer(ictx);
2371 	ictx->last = -1;
2372 }
2373 
2374 /* APC terminator (ST) received. */
2375 static void
2376 input_exit_apc(struct input_ctx *ictx)
2377 {
2378 	struct screen_write_ctx	*sctx = &ictx->ctx;
2379 	struct window_pane	*wp = ictx->wp;
2380 
2381 	if (ictx->flags & INPUT_DISCARD)
2382 		return;
2383 	log_debug("%s: \"%s\"", __func__, ictx->input_buf);
2384 
2385 	if (screen_set_title(sctx->s, ictx->input_buf) && wp != NULL) {
2386 		notify_pane("pane-title-changed", wp);
2387 		server_redraw_window_borders(wp->window);
2388 		server_status_window(wp->window);
2389 	}
2390 }
2391 
2392 /* Rename string started. */
2393 static void
2394 input_enter_rename(struct input_ctx *ictx)
2395 {
2396 	log_debug("%s", __func__);
2397 
2398 	input_clear(ictx);
2399 	input_start_timer(ictx);
2400 	ictx->last = -1;
2401 }
2402 
2403 /* Rename terminator (ST) received. */
2404 static void
2405 input_exit_rename(struct input_ctx *ictx)
2406 {
2407 	struct window_pane	*wp = ictx->wp;
2408 	struct window		*w;
2409 	struct options_entry	*o;
2410 
2411 	if (wp == NULL)
2412 		return;
2413 	if (ictx->flags & INPUT_DISCARD)
2414 		return;
2415 	if (!options_get_number(ictx->wp->options, "allow-rename"))
2416 		return;
2417 	log_debug("%s: \"%s\"", __func__, ictx->input_buf);
2418 
2419 	if (!utf8_isvalid(ictx->input_buf))
2420 		return;
2421 	w = wp->window;
2422 
2423 	if (ictx->input_len == 0) {
2424 		o = options_get_only(w->options, "automatic-rename");
2425 		if (o != NULL)
2426 			options_remove_or_default(o, -1, NULL);
2427 		if (!options_get_number(w->options, "automatic-rename"))
2428 			window_set_name(w, "");
2429 	} else {
2430 		options_set_number(w->options, "automatic-rename", 0);
2431 		window_set_name(w, ictx->input_buf);
2432 	}
2433 	server_redraw_window_borders(w);
2434 	server_status_window(w);
2435 }
2436 
2437 /* Open UTF-8 character. */
2438 static int
2439 input_top_bit_set(struct input_ctx *ictx)
2440 {
2441 	struct screen_write_ctx	*sctx = &ictx->ctx;
2442 	struct utf8_data	*ud = &ictx->utf8data;
2443 
2444 	ictx->last = -1;
2445 
2446 	if (!ictx->utf8started) {
2447 		if (utf8_open(ud, ictx->ch) != UTF8_MORE)
2448 			return (0);
2449 		ictx->utf8started = 1;
2450 		return (0);
2451 	}
2452 
2453 	switch (utf8_append(ud, ictx->ch)) {
2454 	case UTF8_MORE:
2455 		return (0);
2456 	case UTF8_ERROR:
2457 		ictx->utf8started = 0;
2458 		return (0);
2459 	case UTF8_DONE:
2460 		break;
2461 	}
2462 	ictx->utf8started = 0;
2463 
2464 	log_debug("%s %hhu '%*s' (width %hhu)", __func__, ud->size,
2465 	    (int)ud->size, ud->data, ud->width);
2466 
2467 	utf8_copy(&ictx->cell.cell.data, ud);
2468 	screen_write_collect_add(sctx, &ictx->cell.cell);
2469 
2470 	return (0);
2471 }
2472 
2473 /* Reply to a colour request. */
2474 static void
2475 input_osc_colour_reply(struct input_ctx *ictx, u_int n, int c)
2476 {
2477     u_char	 r, g, b;
2478     const char	*end;
2479 
2480     if (c != -1)
2481 	    c = colour_force_rgb(c);
2482     if (c == -1)
2483 	    return;
2484     colour_split_rgb(c, &r, &g, &b);
2485 
2486     if (ictx->input_end == INPUT_END_BEL)
2487 	    end = "\007";
2488     else
2489 	    end = "\033\\";
2490     input_reply(ictx, "\033]%u;rgb:%02hhx%02hhx/%02hhx%02hhx/%02hhx%02hhx%s",
2491 	n, r, r, g, g, b, b, end);
2492 }
2493 
2494 /* Handle the OSC 4 sequence for setting (multiple) palette entries. */
2495 static void
2496 input_osc_4(struct input_ctx *ictx, const char *p)
2497 {
2498 	char	*copy, *s, *next = NULL;
2499 	long	 idx;
2500 	int	 c, bad = 0, redraw = 0;
2501 
2502 	copy = s = xstrdup(p);
2503 	while (s != NULL && *s != '\0') {
2504 		idx = strtol(s, &next, 10);
2505 		if (*next++ != ';') {
2506 			bad = 1;
2507 			break;
2508 		}
2509 		if (idx < 0 || idx >= 256) {
2510 			bad = 1;
2511 			break;
2512 		}
2513 
2514 		s = strsep(&next, ";");
2515 		if (strcmp(s, "?") == 0) {
2516 			c = colour_palette_get(ictx->palette, idx);
2517 			if (c != -1)
2518 				input_osc_colour_reply(ictx, 4, c);
2519 			continue;
2520 		}
2521 		if ((c = colour_parseX11(s)) == -1) {
2522 			s = next;
2523 			continue;
2524 		}
2525 		if (colour_palette_set(ictx->palette, idx, c))
2526 			redraw = 1;
2527 		s = next;
2528 	}
2529 	if (bad)
2530 		log_debug("bad OSC 4: %s", p);
2531 	if (redraw)
2532 		screen_write_fullredraw(&ictx->ctx);
2533 	free(copy);
2534 }
2535 
2536 /* Handle the OSC 8 sequence for embedding hyperlinks. */
2537 static void
2538 input_osc_8(struct input_ctx *ictx, const char *p)
2539 {
2540 	struct hyperlinks	*hl = ictx->ctx.s->hyperlinks;
2541 	struct grid_cell	*gc = &ictx->cell.cell;
2542 	const char		*start, *end, *uri;
2543 	char	    		*id = NULL;
2544 
2545 	for (start = p; (end = strpbrk(start, ":;")) != NULL; start = end + 1) {
2546 		if (end - start >= 4 && strncmp(start, "id=", 3) == 0) {
2547 			if (id != NULL)
2548 				goto bad;
2549 			id = xstrndup(start + 3, end - start - 3);
2550 		}
2551 
2552 		/* The first ; is the end of parameters and start of the URI. */
2553 		if (*end == ';')
2554 			break;
2555 	}
2556 	if (end == NULL || *end != ';')
2557 		goto bad;
2558 	uri = end + 1;
2559 	if (*uri == '\0') {
2560 		gc->link = 0;
2561 		free(id);
2562 		return;
2563 	}
2564 	gc->link = hyperlinks_put(hl, uri, id);
2565 	if (id == NULL)
2566 		log_debug("hyperlink (anonymous) %s = %u", uri, gc->link);
2567 	else
2568 		log_debug("hyperlink (id=%s) %s = %u", id, uri, gc->link);
2569 	free(id);
2570 	return;
2571 
2572 bad:
2573 	log_debug("bad OSC 8 %s", p);
2574 	free(id);
2575 }
2576 
2577 /*
2578  * Get a client with a foreground for the pane. There isn't much to choose
2579  * between them so just use the first.
2580  */
2581 static int
2582 input_get_fg_client(struct window_pane *wp)
2583 {
2584 	struct window	*w = wp->window;
2585 	struct client	*loop;
2586 
2587 	TAILQ_FOREACH(loop, &clients, entry) {
2588 		if (loop->flags & CLIENT_UNATTACHEDFLAGS)
2589 			continue;
2590 		if (loop->session == NULL || !session_has(loop->session, w))
2591 			continue;
2592 		if (loop->tty.fg == -1)
2593 			continue;
2594 		return (loop->tty.fg);
2595 	}
2596 	return (-1);
2597 }
2598 
2599 /* Get a client with a background for the pane. */
2600 static int
2601 input_get_bg_client(struct window_pane *wp)
2602 {
2603 	struct window	*w = wp->window;
2604 	struct client	*loop;
2605 
2606 	TAILQ_FOREACH(loop, &clients, entry) {
2607 		if (loop->flags & CLIENT_UNATTACHEDFLAGS)
2608 			continue;
2609 		if (loop->session == NULL || !session_has(loop->session, w))
2610 			continue;
2611 		if (loop->tty.bg == -1)
2612 			continue;
2613 		return (loop->tty.bg);
2614 	}
2615 	return (-1);
2616 }
2617 
2618 /* Handle the OSC 10 sequence for setting and querying foreground colour. */
2619 static void
2620 input_osc_10(struct input_ctx *ictx, const char *p)
2621 {
2622 	struct window_pane	*wp = ictx->wp;
2623 	struct grid_cell	 defaults;
2624 	int			 c;
2625 
2626 	if (strcmp(p, "?") == 0) {
2627 		if (wp == NULL)
2628 			return;
2629 		tty_default_colours(&defaults, wp);
2630 		if (COLOUR_DEFAULT(defaults.fg))
2631 			c = input_get_fg_client(wp);
2632 		else
2633 			c = defaults.fg;
2634 		input_osc_colour_reply(ictx, 10, c);
2635 		return;
2636 	}
2637 
2638 	if ((c = colour_parseX11(p)) == -1) {
2639 		log_debug("bad OSC 10: %s", p);
2640 		return;
2641 	}
2642 	if (ictx->palette != NULL) {
2643 		ictx->palette->fg = c;
2644 		if (wp != NULL)
2645 			wp->flags |= PANE_STYLECHANGED;
2646 		screen_write_fullredraw(&ictx->ctx);
2647 	}
2648 }
2649 
2650 /* Handle the OSC 110 sequence for resetting foreground colour. */
2651 static void
2652 input_osc_110(struct input_ctx *ictx, const char *p)
2653 {
2654 	struct window_pane	*wp = ictx->wp;
2655 
2656 	if (*p != '\0')
2657 		return;
2658 	if (ictx->palette != NULL) {
2659 		ictx->palette->fg = 8;
2660 		if (wp != NULL)
2661 			wp->flags |= PANE_STYLECHANGED;
2662 		screen_write_fullredraw(&ictx->ctx);
2663 	}
2664 }
2665 
2666 /* Handle the OSC 11 sequence for setting and querying background colour. */
2667 static void
2668 input_osc_11(struct input_ctx *ictx, const char *p)
2669 {
2670 	struct window_pane	*wp = ictx->wp;
2671 	struct grid_cell	 defaults;
2672 	int			 c;
2673 
2674 	if (strcmp(p, "?") == 0) {
2675 		if (wp == NULL)
2676 			return;
2677 		tty_default_colours(&defaults, wp);
2678 		if (COLOUR_DEFAULT(defaults.bg))
2679 			c = input_get_bg_client(wp);
2680 		else
2681 			c = defaults.bg;
2682 		input_osc_colour_reply(ictx, 11, c);
2683 		return;
2684 	}
2685 
2686 	if ((c = colour_parseX11(p)) == -1) {
2687 		log_debug("bad OSC 11: %s", p);
2688 		return;
2689 	}
2690 	if (ictx->palette != NULL) {
2691 		ictx->palette->bg = c;
2692 		if (wp != NULL)
2693 			wp->flags |= PANE_STYLECHANGED;
2694 		screen_write_fullredraw(&ictx->ctx);
2695 	}
2696 }
2697 
2698 /* Handle the OSC 111 sequence for resetting background colour. */
2699 static void
2700 input_osc_111(struct input_ctx *ictx, const char *p)
2701 {
2702 	struct window_pane	*wp = ictx->wp;
2703 
2704 	if (*p != '\0')
2705 		return;
2706 	if (ictx->palette != NULL) {
2707 		ictx->palette->bg = 8;
2708 		if (wp != NULL)
2709 			wp->flags |= PANE_STYLECHANGED;
2710 		screen_write_fullredraw(&ictx->ctx);
2711 	}
2712 }
2713 
2714 /* Handle the OSC 12 sequence for setting and querying cursor colour. */
2715 static void
2716 input_osc_12(struct input_ctx *ictx, const char *p)
2717 {
2718 	struct window_pane	*wp = ictx->wp;
2719 	int			 c;
2720 
2721 	if (strcmp(p, "?") == 0) {
2722 		if (wp != NULL) {
2723 			c = ictx->ctx.s->ccolour;
2724 			if (c == -1)
2725 				c = ictx->ctx.s->default_ccolour;
2726 			input_osc_colour_reply(ictx, 12, c);
2727 		}
2728 		return;
2729 	}
2730 
2731 	if ((c = colour_parseX11(p)) == -1) {
2732 		log_debug("bad OSC 12: %s", p);
2733 		return;
2734 	}
2735 	screen_set_cursor_colour(ictx->ctx.s, c);
2736 }
2737 
2738 /* Handle the OSC 112 sequence for resetting cursor colour. */
2739 static void
2740 input_osc_112(struct input_ctx *ictx, const char *p)
2741 {
2742 	if (*p == '\0') /* no arguments allowed */
2743 		screen_set_cursor_colour(ictx->ctx.s, -1);
2744 }
2745 
2746 /* Handle the OSC 133 sequence. */
2747 static void
2748 input_osc_133(struct input_ctx *ictx, const char *p)
2749 {
2750 	struct grid		*gd = ictx->ctx.s->grid;
2751 	u_int			 line = ictx->ctx.s->cy + gd->hsize;
2752 	struct grid_line	*gl;
2753 
2754 	if (line > gd->hsize + gd->sy - 1)
2755 		return;
2756 	gl = grid_get_line(gd, line);
2757 
2758 	switch (*p) {
2759 	case 'A':
2760 		gl->flags |= GRID_LINE_START_PROMPT;
2761 		break;
2762 	case 'C':
2763 		gl->flags |= GRID_LINE_START_OUTPUT;
2764 		break;
2765 	}
2766 }
2767 
2768 /* Handle the OSC 52 sequence for setting the clipboard. */
2769 static void
2770 input_osc_52(struct input_ctx *ictx, const char *p)
2771 {
2772 	struct window_pane	*wp = ictx->wp;
2773 	char			*end;
2774 	const char		*buf = NULL;
2775 	size_t			 len = 0;
2776 	u_char			*out;
2777 	int			 outlen, state;
2778 	struct screen_write_ctx	 ctx;
2779 	struct paste_buffer	*pb;
2780 	const char*              allow = "cpqs01234567";
2781 	char                     flags[sizeof "cpqs01234567"] = "";
2782 	u_int			 i, j = 0;
2783 
2784 	if (wp == NULL)
2785 		return;
2786 	state = options_get_number(global_options, "set-clipboard");
2787 	if (state != 2)
2788 		return;
2789 
2790 	if ((end = strchr(p, ';')) == NULL)
2791 		return;
2792 	end++;
2793 	if (*end == '\0')
2794 		return;
2795 	log_debug("%s: %s", __func__, end);
2796 
2797 	for (i = 0; p + i != end; i++) {
2798 		if (strchr(allow, p[i]) != NULL && strchr(flags, p[i]) == NULL)
2799 			flags[j++] = p[i];
2800 	}
2801 	log_debug("%s: %.*s %s", __func__, (int)(end - p - 1), p, flags);
2802 
2803 	if (strcmp(end, "?") == 0) {
2804 		if ((pb = paste_get_top(NULL)) != NULL)
2805 			buf = paste_buffer_data(pb, &len);
2806 		if (ictx->input_end == INPUT_END_BEL)
2807 			input_reply_clipboard(ictx->event, buf, len, "\007");
2808 		else
2809 			input_reply_clipboard(ictx->event, buf, len, "\033\\");
2810 		return;
2811 	}
2812 
2813 	len = (strlen(end) / 4) * 3;
2814 	if (len == 0)
2815 		return;
2816 
2817 	out = xmalloc(len);
2818 	if ((outlen = b64_pton(end, out, len)) == -1) {
2819 		free(out);
2820 		return;
2821 	}
2822 
2823 	screen_write_start_pane(&ctx, wp, NULL);
2824 	screen_write_setselection(&ctx, flags, out, outlen);
2825 	screen_write_stop(&ctx);
2826 	notify_pane("pane-set-clipboard", wp);
2827 
2828 	paste_add(NULL, out, outlen);
2829 }
2830 
2831 /* Handle the OSC 104 sequence for unsetting (multiple) palette entries. */
2832 static void
2833 input_osc_104(struct input_ctx *ictx, const char *p)
2834 {
2835 	char	*copy, *s;
2836 	long	 idx;
2837 	int	 bad = 0, redraw = 0;
2838 
2839 	if (*p == '\0') {
2840 		colour_palette_clear(ictx->palette);
2841 		screen_write_fullredraw(&ictx->ctx);
2842 		return;
2843 	}
2844 
2845 	copy = s = xstrdup(p);
2846 	while (*s != '\0') {
2847 		idx = strtol(s, &s, 10);
2848 		if (*s != '\0' && *s != ';') {
2849 			bad = 1;
2850 			break;
2851 		}
2852 		if (idx < 0 || idx >= 256) {
2853 			bad = 1;
2854 			break;
2855 		}
2856 		if (colour_palette_set(ictx->palette, idx, -1))
2857 			redraw = 1;
2858 		if (*s == ';')
2859 			s++;
2860 	}
2861 	if (bad)
2862 		log_debug("bad OSC 104: %s", p);
2863 	if (redraw)
2864 		screen_write_fullredraw(&ictx->ctx);
2865 	free(copy);
2866 }
2867 
2868 void
2869 input_reply_clipboard(struct bufferevent *bev, const char *buf, size_t len,
2870     const char *end)
2871 {
2872 	char	*out = NULL;
2873 	int	 outlen = 0;
2874 
2875 	if (buf != NULL && len != 0) {
2876 		if (len >= ((size_t)INT_MAX * 3 / 4) - 1)
2877 			return;
2878 		outlen = 4 * ((len + 2) / 3) + 1;
2879 		out = xmalloc(outlen);
2880 		if ((outlen = b64_ntop(buf, len, out, outlen)) == -1) {
2881 			free(out);
2882 			return;
2883 		}
2884 	}
2885 
2886 	bufferevent_write(bev, "\033]52;;", 6);
2887 	if (outlen != 0)
2888 		bufferevent_write(bev, out, outlen);
2889 	bufferevent_write(bev, end, strlen(end));
2890 	free(out);
2891 }
2892