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