1 /*
2  * Copyright © 2008 Kristian Høgsberg
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23 
24 #include <config.h>
25 
26 #include <stdbool.h>
27 #include <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <math.h>
34 #include <time.h>
35 #if defined(__FreeBSD__)
36 #include <libutil.h>
37 #include <sys/ttycom.h>
38 #else
39 #include <pty.h>
40 #endif
41 #include <ctype.h>
42 #include <cairo.h>
43 #if !defined(__FreeBSD__)
44 #include <sys/epoll.h>
45 #endif
46 #include <wchar.h>
47 #include <locale.h>
48 #include <errno.h>
49 
50 #include <linux/input.h>
51 
52 #include <wayland-client.h>
53 
54 #include "shared/config-parser.h"
55 #include "shared/helpers.h"
56 #include "window.h"
57 
58 static int option_fullscreen;
59 static char *option_font;
60 static int option_font_size;
61 static char *option_term;
62 static char *option_shell;
63 
64 static struct wl_list terminal_list;
65 
66 static struct terminal *
67 terminal_create(struct display *display);
68 static void
69 terminal_destroy(struct terminal *terminal);
70 static int
71 terminal_run(struct terminal *terminal, const char *path);
72 
73 #define TERMINAL_DRAW_SINGLE_WIDE_CHARACTERS    \
74     " !\"#$%&'()*+,-./"                         \
75     "0123456789"                                \
76     ":;<=>?@"                                   \
77     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"                \
78     "[\\]^_`"                                   \
79     "abcdefghijklmnopqrstuvwxyz"                \
80     "{|}~"                                      \
81     ""
82 
83 #define MOD_SHIFT	0x01
84 #define MOD_ALT		0x02
85 #define MOD_CTRL	0x04
86 
87 #define ATTRMASK_BOLD		0x01
88 #define ATTRMASK_UNDERLINE	0x02
89 #define ATTRMASK_BLINK		0x04
90 #define ATTRMASK_INVERSE	0x08
91 #define ATTRMASK_CONCEALED	0x10
92 
93 /* Buffer sizes */
94 #define MAX_RESPONSE		256
95 #define MAX_ESCAPE		255
96 
97 /* Terminal modes */
98 #define MODE_SHOW_CURSOR	0x00000001
99 #define MODE_INVERSE		0x00000002
100 #define MODE_AUTOWRAP		0x00000004
101 #define MODE_AUTOREPEAT		0x00000008
102 #define MODE_LF_NEWLINE		0x00000010
103 #define MODE_IRM		0x00000020
104 #define MODE_DELETE_SENDS_DEL	0x00000040
105 #define MODE_ALT_SENDS_ESC	0x00000080
106 
107 union utf8_char {
108 	unsigned char byte[4];
109 	uint32_t ch;
110 };
111 
112 enum utf8_state {
113 	utf8state_start,
114 	utf8state_accept,
115 	utf8state_reject,
116 	utf8state_expect3,
117 	utf8state_expect2,
118 	utf8state_expect1
119 };
120 
121 struct utf8_state_machine {
122 	enum utf8_state state;
123 	int len;
124 	union utf8_char s;
125 	uint32_t unicode;
126 };
127 
128 static void
init_state_machine(struct utf8_state_machine * machine)129 init_state_machine(struct utf8_state_machine *machine)
130 {
131 	machine->state = utf8state_start;
132 	machine->len = 0;
133 	machine->s.ch = 0;
134 }
135 
136 static enum utf8_state
utf8_next_char(struct utf8_state_machine * machine,unsigned char c)137 utf8_next_char(struct utf8_state_machine *machine, unsigned char c)
138 {
139 	switch(machine->state) {
140 	case utf8state_start:
141 	case utf8state_accept:
142 	case utf8state_reject:
143 		machine->s.ch = 0;
144 		machine->len = 0;
145 		if (c == 0xC0 || c == 0xC1) {
146 			/* overlong encoding, reject */
147 			machine->state = utf8state_reject;
148 		} else if ((c & 0x80) == 0) {
149 			/* single byte, accept */
150 			machine->s.byte[machine->len++] = c;
151 			machine->state = utf8state_accept;
152 			machine->unicode = c;
153 		} else if ((c & 0xC0) == 0x80) {
154 			/* parser out of sync, ignore byte */
155 			machine->state = utf8state_start;
156 		} else if ((c & 0xE0) == 0xC0) {
157 			/* start of two byte sequence */
158 			machine->s.byte[machine->len++] = c;
159 			machine->state = utf8state_expect1;
160 			machine->unicode = c & 0x1f;
161 		} else if ((c & 0xF0) == 0xE0) {
162 			/* start of three byte sequence */
163 			machine->s.byte[machine->len++] = c;
164 			machine->state = utf8state_expect2;
165 			machine->unicode = c & 0x0f;
166 		} else if ((c & 0xF8) == 0xF0) {
167 			/* start of four byte sequence */
168 			machine->s.byte[machine->len++] = c;
169 			machine->state = utf8state_expect3;
170 			machine->unicode = c & 0x07;
171 		} else {
172 			/* overlong encoding, reject */
173 			machine->state = utf8state_reject;
174 		}
175 		break;
176 	case utf8state_expect3:
177 		machine->s.byte[machine->len++] = c;
178 		machine->unicode = (machine->unicode << 6) | (c & 0x3f);
179 		if ((c & 0xC0) == 0x80) {
180 			/* all good, continue */
181 			machine->state = utf8state_expect2;
182 		} else {
183 			/* missing extra byte, reject */
184 			machine->state = utf8state_reject;
185 		}
186 		break;
187 	case utf8state_expect2:
188 		machine->s.byte[machine->len++] = c;
189 		machine->unicode = (machine->unicode << 6) | (c & 0x3f);
190 		if ((c & 0xC0) == 0x80) {
191 			/* all good, continue */
192 			machine->state = utf8state_expect1;
193 		} else {
194 			/* missing extra byte, reject */
195 			machine->state = utf8state_reject;
196 		}
197 		break;
198 	case utf8state_expect1:
199 		machine->s.byte[machine->len++] = c;
200 		machine->unicode = (machine->unicode << 6) | (c & 0x3f);
201 		if ((c & 0xC0) == 0x80) {
202 			/* all good, accept */
203 			machine->state = utf8state_accept;
204 		} else {
205 			/* missing extra byte, reject */
206 			machine->state = utf8state_reject;
207 		}
208 		break;
209 	default:
210 		machine->state = utf8state_reject;
211 		break;
212 	}
213 
214 	return machine->state;
215 }
216 
217 static uint32_t
get_unicode(union utf8_char utf8)218 get_unicode(union utf8_char utf8)
219 {
220 	struct utf8_state_machine machine;
221 	int i;
222 
223 	init_state_machine(&machine);
224 	for (i = 0; i < 4; i++) {
225 		utf8_next_char(&machine, utf8.byte[i]);
226 		if (machine.state == utf8state_accept ||
227 		    machine.state == utf8state_reject)
228 			break;
229 	}
230 
231 	if (machine.state == utf8state_reject)
232 		return 0xfffd;
233 
234 	return machine.unicode;
235 }
236 
237 static bool
is_wide(union utf8_char utf8)238 is_wide(union utf8_char utf8)
239 {
240 	uint32_t unichar = get_unicode(utf8);
241 	return wcwidth(unichar) > 1;
242 }
243 
244 struct char_sub {
245 	union utf8_char match;
246 	union utf8_char replace;
247 };
248 /* Set last char_sub match to NULL char */
249 typedef struct char_sub *character_set;
250 
251 struct char_sub CS_US[] = {
252 	{{{0, }}, {{0, }}}
253 };
254 static struct char_sub CS_UK[] = {
255 	{{{'#', 0, }}, {{0xC2, 0xA3, 0, }}}, /* POUND: £ */
256 	{{{0, }}, {{0, }}}
257 };
258 static struct char_sub CS_SPECIAL[] = {
259 	{{{'`', 0, }}, {{0xE2, 0x99, 0xA6, 0}}}, /* diamond: ♦ */
260 	{{{'a', 0, }}, {{0xE2, 0x96, 0x92, 0}}}, /* 50% cell: ▒ */
261 	{{{'b', 0, }}, {{0xE2, 0x90, 0x89, 0}}}, /* HT: ␉ */
262 	{{{'c', 0, }}, {{0xE2, 0x90, 0x8C, 0}}}, /* FF: ␌ */
263 	{{{'d', 0, }}, {{0xE2, 0x90, 0x8D, 0}}}, /* CR: ␍ */
264 	{{{'e', 0, }}, {{0xE2, 0x90, 0x8A, 0}}}, /* LF: ␊ */
265 	{{{'f', 0, }}, {{0xC2, 0xB0, 0, }}}, /* Degree: ° */
266 	{{{'g', 0, }}, {{0xC2, 0xB1, 0, }}}, /* Plus/Minus: ± */
267 	{{{'h', 0, }}, {{0xE2, 0x90, 0xA4, 0}}}, /* NL: ␤ */
268 	{{{'i', 0, }}, {{0xE2, 0x90, 0x8B, 0}}}, /* VT: ␋ */
269 	{{{'j', 0, }}, {{0xE2, 0x94, 0x98, 0}}}, /* CN_RB: ┘ */
270 	{{{'k', 0, }}, {{0xE2, 0x94, 0x90, 0}}}, /* CN_RT: ┐ */
271 	{{{'l', 0, }}, {{0xE2, 0x94, 0x8C, 0}}}, /* CN_LT: ┌ */
272 	{{{'m', 0, }}, {{0xE2, 0x94, 0x94, 0}}}, /* CN_LB: └ */
273 	{{{'n', 0, }}, {{0xE2, 0x94, 0xBC, 0}}}, /* CROSS: ┼ */
274 	{{{'o', 0, }}, {{0xE2, 0x8E, 0xBA, 0}}}, /* Horiz. Scan Line 1: ⎺ */
275 	{{{'p', 0, }}, {{0xE2, 0x8E, 0xBB, 0}}}, /* Horiz. Scan Line 3: ⎻ */
276 	{{{'q', 0, }}, {{0xE2, 0x94, 0x80, 0}}}, /* Horiz. Scan Line 5: ─ */
277 	{{{'r', 0, }}, {{0xE2, 0x8E, 0xBC, 0}}}, /* Horiz. Scan Line 7: ⎼ */
278 	{{{'s', 0, }}, {{0xE2, 0x8E, 0xBD, 0}}}, /* Horiz. Scan Line 9: ⎽ */
279 	{{{'t', 0, }}, {{0xE2, 0x94, 0x9C, 0}}}, /* TR: ├ */
280 	{{{'u', 0, }}, {{0xE2, 0x94, 0xA4, 0}}}, /* TL: ┤ */
281 	{{{'v', 0, }}, {{0xE2, 0x94, 0xB4, 0}}}, /* TU: ┴ */
282 	{{{'w', 0, }}, {{0xE2, 0x94, 0xAC, 0}}}, /* TD: ┬ */
283 	{{{'x', 0, }}, {{0xE2, 0x94, 0x82, 0}}}, /* V: │ */
284 	{{{'y', 0, }}, {{0xE2, 0x89, 0xA4, 0}}}, /* LE: ≤ */
285 	{{{'z', 0, }}, {{0xE2, 0x89, 0xA5, 0}}}, /* GE: ≥ */
286 	{{{'{', 0, }}, {{0xCF, 0x80, 0, }}}, /* PI: π */
287 	{{{'|', 0, }}, {{0xE2, 0x89, 0xA0, 0}}}, /* NEQ: ≠ */
288 	{{{'}', 0, }}, {{0xC2, 0xA3, 0, }}}, /* POUND: £ */
289 	{{{'~', 0, }}, {{0xE2, 0x8B, 0x85, 0}}}, /* DOT: ⋅ */
290 	{{{0, }}, {{0, }}}
291 };
292 
293 static void
apply_char_set(character_set cs,union utf8_char * utf8)294 apply_char_set(character_set cs, union utf8_char *utf8)
295 {
296 	int i = 0;
297 
298 	while (cs[i].match.byte[0]) {
299 		if ((*utf8).ch == cs[i].match.ch) {
300 			*utf8 = cs[i].replace;
301 			break;
302 		}
303 		i++;
304 	}
305 }
306 
307 struct key_map {
308 	int sym;
309 	int num;
310 	char escape;
311 	char code;
312 };
313 /* Set last key_sub sym to NULL */
314 typedef struct key_map *keyboard_mode;
315 
316 static struct key_map KM_NORMAL[] = {
317 	{ XKB_KEY_Left,  1, '[', 'D' },
318 	{ XKB_KEY_Right, 1, '[', 'C' },
319 	{ XKB_KEY_Up,    1, '[', 'A' },
320 	{ XKB_KEY_Down,  1, '[', 'B' },
321 	{ XKB_KEY_Home,  1, '[', 'H' },
322 	{ XKB_KEY_End,   1, '[', 'F' },
323 	{ 0, 0, 0, 0 }
324 };
325 static struct key_map KM_APPLICATION[] = {
326 	{ XKB_KEY_Left,          1, 'O', 'D' },
327 	{ XKB_KEY_Right,         1, 'O', 'C' },
328 	{ XKB_KEY_Up,            1, 'O', 'A' },
329 	{ XKB_KEY_Down,          1, 'O', 'B' },
330 	{ XKB_KEY_Home,          1, 'O', 'H' },
331 	{ XKB_KEY_End,           1, 'O', 'F' },
332 	{ XKB_KEY_KP_Enter,      1, 'O', 'M' },
333 	{ XKB_KEY_KP_Multiply,   1, 'O', 'j' },
334 	{ XKB_KEY_KP_Add,        1, 'O', 'k' },
335 	{ XKB_KEY_KP_Separator,  1, 'O', 'l' },
336 	{ XKB_KEY_KP_Subtract,   1, 'O', 'm' },
337 	{ XKB_KEY_KP_Divide,     1, 'O', 'o' },
338 	{ 0, 0, 0, 0 }
339 };
340 
341 static int
function_key_response(char escape,int num,uint32_t modifiers,char code,char * response)342 function_key_response(char escape, int num, uint32_t modifiers,
343 		      char code, char *response)
344 {
345 	int mod_num = 0;
346 	int len;
347 
348 	if (modifiers & MOD_SHIFT_MASK) mod_num   |= 1;
349 	if (modifiers & MOD_ALT_MASK) mod_num    |= 2;
350 	if (modifiers & MOD_CONTROL_MASK) mod_num |= 4;
351 
352 	if (mod_num != 0)
353 		len = snprintf(response, MAX_RESPONSE, "\e[%d;%d%c",
354 			       num, mod_num + 1, code);
355 	else if (code != '~')
356 		len = snprintf(response, MAX_RESPONSE, "\e%c%c",
357 			       escape, code);
358 	else
359 		len = snprintf(response, MAX_RESPONSE, "\e%c%d%c",
360 			       escape, num, code);
361 
362 	if (len >= MAX_RESPONSE)	return MAX_RESPONSE - 1;
363 	else				return len;
364 }
365 
366 /* returns the number of bytes written into response,
367  * which must have room for MAX_RESPONSE bytes */
368 static int
apply_key_map(keyboard_mode mode,int sym,uint32_t modifiers,char * response)369 apply_key_map(keyboard_mode mode, int sym, uint32_t modifiers, char *response)
370 {
371 	struct key_map map;
372 	int len = 0;
373 	int i = 0;
374 
375 	while (mode[i].sym) {
376 		map = mode[i++];
377 		if (sym == map.sym) {
378 			len = function_key_response(map.escape, map.num,
379 						    modifiers, map.code,
380 						    response);
381 			break;
382 		}
383 	}
384 
385 	return len;
386 }
387 
388 struct terminal_color { double r, g, b, a; };
389 struct attr {
390 	unsigned char fg, bg;
391 	char a;        /* attributes format:
392 	                * 76543210
393 			*    cilub */
394 	char s;        /* in selection */
395 };
396 struct color_scheme {
397 	struct terminal_color palette[16];
398 	char border;
399 	struct attr default_attr;
400 };
401 
402 static void
attr_init(struct attr * data_attr,struct attr attr,int n)403 attr_init(struct attr *data_attr, struct attr attr, int n)
404 {
405 	int i;
406 	for (i = 0; i < n; i++) {
407 		data_attr[i] = attr;
408 	}
409 }
410 
411 enum escape_state {
412 	escape_state_normal = 0,
413 	escape_state_escape,
414 	escape_state_dcs,
415 	escape_state_csi,
416 	escape_state_osc,
417 	escape_state_inner_escape,
418 	escape_state_ignore,
419 	escape_state_special
420 };
421 
422 #define ESC_FLAG_WHAT	0x01
423 #define ESC_FLAG_GT	0x02
424 #define ESC_FLAG_BANG	0x04
425 #define ESC_FLAG_CASH	0x08
426 #define ESC_FLAG_SQUOTE 0x10
427 #define ESC_FLAG_DQUOTE	0x20
428 #define ESC_FLAG_SPACE	0x40
429 
430 enum {
431 	SELECT_NONE,
432 	SELECT_CHAR,
433 	SELECT_WORD,
434 	SELECT_LINE
435 };
436 
437 struct terminal {
438 	struct window *window;
439 	struct widget *widget;
440 	struct display *display;
441 	char *title;
442 	union utf8_char *data;
443 	struct task io_task;
444 	char *tab_ruler;
445 	struct attr *data_attr;
446 	struct attr curr_attr;
447 	uint32_t mode;
448 	char origin_mode;
449 	char saved_origin_mode;
450 	struct attr saved_attr;
451 	union utf8_char last_char;
452 	int margin_top, margin_bottom;
453 	character_set cs, g0, g1;
454 	character_set saved_cs, saved_g0, saved_g1;
455 	keyboard_mode key_mode;
456 	int data_pitch, attr_pitch;  /* The width in bytes of a line */
457 	int width, height, row, column, max_width;
458 	uint32_t buffer_height;
459 	uint32_t start, end, saved_start, log_size;
460 	wl_fixed_t smooth_scroll;
461 	int saved_row, saved_column;
462 	int scrolling;
463 	int send_cursor_position;
464 	int fd, master;
465 	struct event *masterev;
466 	uint32_t modifiers;
467 	char escape[MAX_ESCAPE+1];
468 	int escape_length;
469 	enum escape_state state;
470 	enum escape_state outer_state;
471 	int escape_flags;
472 	struct utf8_state_machine state_machine;
473 	int margin;
474 	struct color_scheme *color_scheme;
475 	struct terminal_color color_table[256];
476 	cairo_font_extents_t extents;
477 	double average_width;
478 	cairo_scaled_font_t *font_normal, *font_bold;
479 	uint32_t hide_cursor_serial;
480 	int size_in_title;
481 
482 	struct wl_data_source *selection;
483 	uint32_t click_time;
484 	int dragging, click_count;
485 	int selection_start_x, selection_start_y;
486 	int selection_end_x, selection_end_y;
487 	int selection_start_row, selection_start_col;
488 	int selection_end_row, selection_end_col;
489 	struct wl_list link;
490 };
491 
492 /* Create default tab stops, every 8 characters */
493 static void
terminal_init_tabs(struct terminal * terminal)494 terminal_init_tabs(struct terminal *terminal)
495 {
496 	int i = 0;
497 
498 	while (i < terminal->width) {
499 		if (i % 8 == 0)
500 			terminal->tab_ruler[i] = 1;
501 		else
502 			terminal->tab_ruler[i] = 0;
503 		i++;
504 	}
505 }
506 
507 static void
terminal_init(struct terminal * terminal)508 terminal_init(struct terminal *terminal)
509 {
510 	terminal->curr_attr = terminal->color_scheme->default_attr;
511 	terminal->origin_mode = 0;
512 	terminal->mode = MODE_SHOW_CURSOR |
513 			 MODE_AUTOREPEAT |
514 			 MODE_ALT_SENDS_ESC |
515 			 MODE_AUTOWRAP;
516 
517 	terminal->row = 0;
518 	terminal->column = 0;
519 
520 	terminal->g0 = CS_US;
521 	terminal->g1 = CS_US;
522 	terminal->cs = terminal->g0;
523 	terminal->key_mode = KM_NORMAL;
524 
525 	terminal->saved_g0 = terminal->g0;
526 	terminal->saved_g1 = terminal->g1;
527 	terminal->saved_cs = terminal->cs;
528 
529 	terminal->saved_attr = terminal->curr_attr;
530 	terminal->saved_origin_mode = terminal->origin_mode;
531 	terminal->saved_row = terminal->row;
532 	terminal->saved_column = terminal->column;
533 
534 	if (terminal->tab_ruler != NULL) terminal_init_tabs(terminal);
535 }
536 
537 static void
init_color_table(struct terminal * terminal)538 init_color_table(struct terminal *terminal)
539 {
540 	int c, r;
541 	struct terminal_color *color_table = terminal->color_table;
542 
543 	for (c = 0; c < 256; c ++) {
544 		if (c < 16) {
545 			color_table[c] = terminal->color_scheme->palette[c];
546 		} else if (c < 232) {
547 			r = c - 16;
548 			color_table[c].b = ((double)(r % 6) / 6.0); r /= 6;
549 			color_table[c].g = ((double)(r % 6) / 6.0); r /= 6;
550 			color_table[c].r = ((double)(r % 6) / 6.0);
551 			color_table[c].a = 1.0;
552 		} else {
553 			r = (c - 232) * 10 + 8;
554 			color_table[c].r = ((double) r) / 256.0;
555 			color_table[c].g = color_table[c].r;
556 			color_table[c].b = color_table[c].r;
557 			color_table[c].a = 1.0;
558 		}
559 	}
560 }
561 
562 static union utf8_char *
terminal_get_row(struct terminal * terminal,int row)563 terminal_get_row(struct terminal *terminal, int row)
564 {
565 	int index;
566 
567 	index = (row + terminal->start) & (terminal->buffer_height - 1);
568 
569 	return (void *) terminal->data + index * terminal->data_pitch;
570 }
571 
572 static struct attr*
terminal_get_attr_row(struct terminal * terminal,int row)573 terminal_get_attr_row(struct terminal *terminal, int row)
574 {
575 	int index;
576 
577 	index = (row + terminal->start) & (terminal->buffer_height - 1);
578 
579 	return (void *) terminal->data_attr + index * terminal->attr_pitch;
580 }
581 
582 union decoded_attr {
583 	struct attr attr;
584 	uint32_t key;
585 };
586 
587 static void
terminal_decode_attr(struct terminal * terminal,int row,int col,union decoded_attr * decoded)588 terminal_decode_attr(struct terminal *terminal, int row, int col,
589 		     union decoded_attr *decoded)
590 {
591 	struct attr attr;
592 	int foreground, background, tmp;
593 
594 	decoded->attr.s = 0;
595 	if (((row == terminal->selection_start_row &&
596 	      col >= terminal->selection_start_col) ||
597 	     row > terminal->selection_start_row) &&
598 	    ((row == terminal->selection_end_row &&
599 	      col < terminal->selection_end_col) ||
600 	     row < terminal->selection_end_row))
601 		decoded->attr.s = 1;
602 
603 	/* get the attributes for this character cell */
604 	attr = terminal_get_attr_row(terminal, row)[col];
605 	if ((attr.a & ATTRMASK_INVERSE) ||
606 	    decoded->attr.s ||
607 	    ((terminal->mode & MODE_SHOW_CURSOR) &&
608 	     window_has_focus(terminal->window) && terminal->row == row &&
609 	     terminal->column == col)) {
610 		foreground = attr.bg;
611 		background = attr.fg;
612 		if (attr.a & ATTRMASK_BOLD) {
613 			if (foreground <= 16) foreground |= 0x08;
614 			if (background <= 16) background &= 0x07;
615 		}
616 	} else {
617 		foreground = attr.fg;
618 		background = attr.bg;
619 	}
620 
621 	if (terminal->mode & MODE_INVERSE) {
622 		tmp = foreground;
623 		foreground = background;
624 		background = tmp;
625 		if (attr.a & ATTRMASK_BOLD) {
626 			if (foreground <= 16) foreground |= 0x08;
627 			if (background <= 16) background &= 0x07;
628 		}
629 	}
630 
631 	decoded->attr.fg = foreground;
632 	decoded->attr.bg = background;
633 	decoded->attr.a = attr.a;
634 }
635 
636 
637 static void
terminal_scroll_buffer(struct terminal * terminal,int d)638 terminal_scroll_buffer(struct terminal *terminal, int d)
639 {
640 	int i;
641 
642 	terminal->start += d;
643 	if (d < 0) {
644 		d = 0 - d;
645 		for (i = 0; i < d; i++) {
646 			memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
647 			attr_init(terminal_get_attr_row(terminal, i),
648 			    terminal->curr_attr, terminal->width);
649 		}
650 	} else {
651 		for (i = terminal->height - d; i < terminal->height; i++) {
652 			memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
653 			attr_init(terminal_get_attr_row(terminal, i),
654 			    terminal->curr_attr, terminal->width);
655 		}
656 	}
657 
658 	terminal->selection_start_row -= d;
659 	terminal->selection_end_row -= d;
660 }
661 
662 static void
terminal_scroll_window(struct terminal * terminal,int d)663 terminal_scroll_window(struct terminal *terminal, int d)
664 {
665 	int i;
666 	int window_height;
667 	int from_row, to_row;
668 
669 	// scrolling range is inclusive
670 	window_height = terminal->margin_bottom - terminal->margin_top + 1;
671 	d = d % (window_height + 1);
672 	if (d < 0) {
673 		d = 0 - d;
674 		to_row = terminal->margin_bottom;
675 		from_row = terminal->margin_bottom - d;
676 
677 		for (i = 0; i < (window_height - d); i++) {
678 			memcpy(terminal_get_row(terminal, to_row - i),
679 			       terminal_get_row(terminal, from_row - i),
680 			       terminal->data_pitch);
681 			memcpy(terminal_get_attr_row(terminal, to_row - i),
682 			       terminal_get_attr_row(terminal, from_row - i),
683 			       terminal->attr_pitch);
684 		}
685 		for (i = terminal->margin_top; i < (terminal->margin_top + d); i++) {
686 			memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
687 			attr_init(terminal_get_attr_row(terminal, i),
688 				terminal->curr_attr, terminal->width);
689 		}
690 	} else {
691 		to_row = terminal->margin_top;
692 		from_row = terminal->margin_top + d;
693 
694 		for (i = 0; i < (window_height - d); i++) {
695 			memcpy(terminal_get_row(terminal, to_row + i),
696 			       terminal_get_row(terminal, from_row + i),
697 			       terminal->data_pitch);
698 			memcpy(terminal_get_attr_row(terminal, to_row + i),
699 			       terminal_get_attr_row(terminal, from_row + i),
700 			       terminal->attr_pitch);
701 		}
702 		for (i = terminal->margin_bottom - d + 1; i <= terminal->margin_bottom; i++) {
703 			memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
704 			attr_init(terminal_get_attr_row(terminal, i),
705 				terminal->curr_attr, terminal->width);
706 		}
707 	}
708 }
709 
710 static void
terminal_scroll(struct terminal * terminal,int d)711 terminal_scroll(struct terminal *terminal, int d)
712 {
713 	if (terminal->margin_top == 0 && terminal->margin_bottom == terminal->height - 1)
714 		terminal_scroll_buffer(terminal, d);
715 	else
716 		terminal_scroll_window(terminal, d);
717 }
718 
719 static void
terminal_shift_line(struct terminal * terminal,int d)720 terminal_shift_line(struct terminal *terminal, int d)
721 {
722 	union utf8_char *row;
723 	struct attr *attr_row;
724 
725 	row = terminal_get_row(terminal, terminal->row);
726 	attr_row = terminal_get_attr_row(terminal, terminal->row);
727 
728 	if ((terminal->width + d) <= terminal->column)
729 		d = terminal->column + 1 - terminal->width;
730 	if ((terminal->column + d) >= terminal->width)
731 		d = terminal->width - terminal->column - 1;
732 
733 	if (d < 0) {
734 		d = 0 - d;
735 		memmove(&row[terminal->column],
736 		        &row[terminal->column + d],
737 			(terminal->width - terminal->column - d) * sizeof(union utf8_char));
738 		memmove(&attr_row[terminal->column], &attr_row[terminal->column + d],
739 		        (terminal->width - terminal->column - d) * sizeof(struct attr));
740 		memset(&row[terminal->width - d], 0, d * sizeof(union utf8_char));
741 		attr_init(&attr_row[terminal->width - d], terminal->curr_attr, d);
742 	} else {
743 		memmove(&row[terminal->column + d], &row[terminal->column],
744 			(terminal->width - terminal->column - d) * sizeof(union utf8_char));
745 		memmove(&attr_row[terminal->column + d], &attr_row[terminal->column],
746 			(terminal->width - terminal->column - d) * sizeof(struct attr));
747 		memset(&row[terminal->column], 0, d * sizeof(union utf8_char));
748 		attr_init(&attr_row[terminal->column], terminal->curr_attr, d);
749 	}
750 }
751 
752 static void
terminal_resize_cells(struct terminal * terminal,int width,int height)753 terminal_resize_cells(struct terminal *terminal,
754 		      int width, int height)
755 {
756 	union utf8_char *data;
757 	struct attr *data_attr;
758 	char *tab_ruler;
759 	int data_pitch, attr_pitch;
760 	int i, l, total_rows;
761 	uint32_t d, uheight = height;
762 	struct rectangle allocation;
763 	struct winsize ws;
764 
765 	if (uheight > terminal->buffer_height)
766 		height = terminal->buffer_height;
767 
768 	if (terminal->width == width && terminal->height == height)
769 		return;
770 
771 	if (terminal->data && width <= terminal->max_width) {
772 		d = 0;
773 		if (height < terminal->height && height <= terminal->row)
774 			d = terminal->height - height;
775 		else if (height > terminal->height &&
776 			 terminal->height - 1 == terminal->row) {
777 			d = terminal->height - height;
778 			if (terminal->log_size < uheight)
779 				d = -terminal->start;
780 		}
781 
782 		terminal->start += d;
783 		terminal->row -= d;
784 	} else {
785 		terminal->max_width = width;
786 		data_pitch = width * sizeof(union utf8_char);
787 		data = xzalloc(data_pitch * terminal->buffer_height);
788 		attr_pitch = width * sizeof(struct attr);
789 		data_attr = xmalloc(attr_pitch * terminal->buffer_height);
790 		tab_ruler = xzalloc(width);
791 		attr_init(data_attr, terminal->curr_attr,
792 			  width * terminal->buffer_height);
793 
794 		if (terminal->data && terminal->data_attr) {
795 			if (width > terminal->width)
796 				l = terminal->width;
797 			else
798 				l = width;
799 
800 			if (terminal->height > height) {
801 				total_rows = height;
802 				i = 1 + terminal->row - height;
803 				if (i > 0) {
804 					terminal->start += i;
805 					terminal->row = terminal->row - i;
806 				}
807 			} else {
808 				total_rows = terminal->height;
809 			}
810 
811 			for (i = 0; i < total_rows; i++) {
812 				memcpy(&data[width * i],
813 				       terminal_get_row(terminal, i),
814 				       l * sizeof(union utf8_char));
815 				memcpy(&data_attr[width * i],
816 				       terminal_get_attr_row(terminal, i),
817 				       l * sizeof(struct attr));
818 			}
819 
820 			free(terminal->data);
821 			free(terminal->data_attr);
822 			free(terminal->tab_ruler);
823 		}
824 
825 		terminal->data_pitch = data_pitch;
826 		terminal->attr_pitch = attr_pitch;
827 		terminal->data = data;
828 		terminal->data_attr = data_attr;
829 		terminal->tab_ruler = tab_ruler;
830 		terminal->start = 0;
831 	}
832 
833 	terminal->margin_bottom =
834 		height - (terminal->height - terminal->margin_bottom);
835 	terminal->width = width;
836 	terminal->height = height;
837 	terminal_init_tabs(terminal);
838 
839 	/* Update the window size */
840 	ws.ws_row = terminal->height;
841 	ws.ws_col = terminal->width;
842 	widget_get_allocation(terminal->widget, &allocation);
843 	ws.ws_xpixel = allocation.width;
844 	ws.ws_ypixel = allocation.height;
845 	ioctl(terminal->master, TIOCSWINSZ, &ws);
846 }
847 
848 static void
update_title(struct terminal * terminal)849 update_title(struct terminal *terminal)
850 {
851 	if (window_is_resizing(terminal->window)) {
852 		char *p;
853 		if (asprintf(&p, "%s — [%dx%d]", terminal->title, terminal->width, terminal->height) > 0) {
854 			window_set_title(terminal->window, p);
855 			free(p);
856 		}
857 	} else {
858 		window_set_title(terminal->window, terminal->title);
859 	}
860 }
861 
862 static void
resize_handler(struct widget * widget,int32_t width,int32_t height,void * data)863 resize_handler(struct widget *widget,
864 	       int32_t width, int32_t height, void *data)
865 {
866 	struct terminal *terminal = data;
867 	int32_t columns, rows, m;
868 
869 	m = 2 * terminal->margin;
870 	columns = (width - m) / (int32_t) terminal->average_width;
871 	rows = (height - m) / (int32_t) terminal->extents.height;
872 
873 	if (!window_is_fullscreen(terminal->window) &&
874 	    !window_is_maximized(terminal->window)) {
875 		width = columns * terminal->average_width + m;
876 		height = rows * terminal->extents.height + m;
877 		widget_set_size(terminal->widget, width, height);
878 	}
879 
880 	terminal_resize_cells(terminal, columns, rows);
881 	update_title(terminal);
882 }
883 
884 static void
state_changed_handler(struct window * window,void * data)885 state_changed_handler(struct window *window, void *data)
886 {
887 	struct terminal *terminal = data;
888 	update_title(terminal);
889 }
890 
891 static void
terminal_resize(struct terminal * terminal,int columns,int rows)892 terminal_resize(struct terminal *terminal, int columns, int rows)
893 {
894 	int32_t width, height, m;
895 
896 	if (window_is_fullscreen(terminal->window) ||
897 	    window_is_maximized(terminal->window))
898 		return;
899 
900 	m = 2 * terminal->margin;
901 	width = columns * terminal->average_width + m;
902 	height = rows * terminal->extents.height + m;
903 
904 	window_frame_set_child_size(terminal->widget, width, height);
905 }
906 
907 struct color_scheme DEFAULT_COLORS = {
908 	{
909 		{0,    0,    0,    1}, /* black */
910 		{0.66, 0,    0,    1}, /* red */
911 		{0  ,  0.66, 0,    1}, /* green */
912 		{0.66, 0.33, 0,    1}, /* orange (nicer than muddy yellow) */
913 		{0  ,  0  ,  0.66, 1}, /* blue */
914 		{0.66, 0  ,  0.66, 1}, /* magenta */
915 		{0,    0.66, 0.66, 1}, /* cyan */
916 		{0.66, 0.66, 0.66, 1}, /* light grey */
917 		{0.22, 0.33, 0.33, 1}, /* dark grey */
918 		{1,    0.33, 0.33, 1}, /* high red */
919 		{0.33, 1,    0.33, 1}, /* high green */
920 		{1,    1,    0.33, 1}, /* high yellow */
921 		{0.33, 0.33, 1,    1}, /* high blue */
922 		{1,    0.33, 1,    1}, /* high magenta */
923 		{0.33, 1,    1,    1}, /* high cyan */
924 		{1,    1,    1,    1}  /* white */
925 	},
926 	0,                             /* black border */
927 	{7, 0, 0, }                    /* bg:black (0), fg:light gray (7)  */
928 };
929 
930 static void
terminal_set_color(struct terminal * terminal,cairo_t * cr,int index)931 terminal_set_color(struct terminal *terminal, cairo_t *cr, int index)
932 {
933 	cairo_set_source_rgba(cr,
934 			      terminal->color_table[index].r,
935 			      terminal->color_table[index].g,
936 			      terminal->color_table[index].b,
937 			      terminal->color_table[index].a);
938 }
939 
940 static void
terminal_send_selection(struct terminal * terminal,int fd)941 terminal_send_selection(struct terminal *terminal, int fd)
942 {
943 	int row, col;
944 	union utf8_char *p_row;
945 	union decoded_attr attr;
946 	FILE *fp;
947 	int len;
948 
949 	fp = fdopen(fd, "w");
950 	if (fp == NULL){
951 		close(fd);
952 		return;
953 	}
954 	for (row = 0; row < terminal->height; row++) {
955 		p_row = terminal_get_row(terminal, row);
956 		for (col = 0; col < terminal->width; col++) {
957 			if (p_row[col].ch == 0x200B) /* space glyph */
958 				continue;
959 			/* get the attributes for this character cell */
960 			terminal_decode_attr(terminal, row, col, &attr);
961 			if (!attr.attr.s)
962 				continue;
963 			len = strnlen((char *) p_row[col].byte, 4);
964 			if (len > 0)
965 				fwrite(p_row[col].byte, 1, len, fp);
966 			if (len == 0 || col == terminal->width - 1) {
967 				fwrite("\n", 1, 1, fp);
968 				break;
969 			}
970 		}
971 	}
972 	fclose(fp);
973 }
974 
975 struct glyph_run {
976 	struct terminal *terminal;
977 	cairo_t *cr;
978 	unsigned int count;
979 	union decoded_attr attr;
980 	cairo_glyph_t glyphs[256], *g;
981 };
982 
983 static void
glyph_run_init(struct glyph_run * run,struct terminal * terminal,cairo_t * cr)984 glyph_run_init(struct glyph_run *run, struct terminal *terminal, cairo_t *cr)
985 {
986 	run->terminal = terminal;
987 	run->cr = cr;
988 	run->g = run->glyphs;
989 	run->count = 0;
990 	run->attr.key = 0;
991 }
992 
993 static void
glyph_run_flush(struct glyph_run * run,union decoded_attr attr)994 glyph_run_flush(struct glyph_run *run, union decoded_attr attr)
995 {
996 	cairo_scaled_font_t *font;
997 
998 	if (run->count > ARRAY_LENGTH(run->glyphs) - 10 ||
999 	    (attr.key != run->attr.key)) {
1000 		if (run->attr.attr.a & (ATTRMASK_BOLD | ATTRMASK_BLINK))
1001 			font = run->terminal->font_bold;
1002 		else
1003 			font = run->terminal->font_normal;
1004 		cairo_set_scaled_font(run->cr, font);
1005 		terminal_set_color(run->terminal, run->cr,
1006 				   run->attr.attr.fg);
1007 
1008 		if (!(run->attr.attr.a & ATTRMASK_CONCEALED))
1009 			cairo_show_glyphs (run->cr, run->glyphs, run->count);
1010 		run->g = run->glyphs;
1011 		run->count = 0;
1012 	}
1013 	run->attr = attr;
1014 }
1015 
1016 static void
glyph_run_add(struct glyph_run * run,int x,int y,union utf8_char * c)1017 glyph_run_add(struct glyph_run *run, int x, int y, union utf8_char *c)
1018 {
1019 	int num_glyphs;
1020 	cairo_scaled_font_t *font;
1021 
1022 	num_glyphs = ARRAY_LENGTH(run->glyphs) - run->count;
1023 
1024 	if (run->attr.attr.a & (ATTRMASK_BOLD | ATTRMASK_BLINK))
1025 		font = run->terminal->font_bold;
1026 	else
1027 		font = run->terminal->font_normal;
1028 
1029 	cairo_move_to(run->cr, x, y);
1030 	cairo_scaled_font_text_to_glyphs (font, x, y,
1031 					  (char *) c->byte, 4,
1032 					  &run->g, &num_glyphs,
1033 					  NULL, NULL, NULL);
1034 	run->g += num_glyphs;
1035 	run->count += num_glyphs;
1036 }
1037 
1038 
1039 static void
redraw_handler(struct widget * widget,void * data)1040 redraw_handler(struct widget *widget, void *data)
1041 {
1042 	struct terminal *terminal = data;
1043 	struct rectangle allocation;
1044 	cairo_t *cr;
1045 	int top_margin, side_margin;
1046 	int row, col, cursor_x, cursor_y;
1047 	union utf8_char *p_row;
1048 	union decoded_attr attr;
1049 	int text_x, text_y;
1050 	cairo_surface_t *surface;
1051 	double d;
1052 	struct glyph_run run;
1053 	cairo_font_extents_t extents;
1054 	double average_width;
1055 	double unichar_width;
1056 
1057 	surface = window_get_surface(terminal->window);
1058 	widget_get_allocation(terminal->widget, &allocation);
1059 	cr = widget_cairo_create(terminal->widget);
1060 	cairo_rectangle(cr, allocation.x, allocation.y,
1061 			allocation.width, allocation.height);
1062 	cairo_clip(cr);
1063 	cairo_push_group(cr);
1064 
1065 	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
1066 	terminal_set_color(terminal, cr, terminal->color_scheme->border);
1067 	cairo_paint(cr);
1068 
1069 	cairo_set_scaled_font(cr, terminal->font_normal);
1070 
1071 	extents = terminal->extents;
1072 	average_width = terminal->average_width;
1073 	side_margin = (allocation.width - terminal->width * average_width) / 2;
1074 	top_margin = (allocation.height - terminal->height * extents.height) / 2;
1075 
1076 	cairo_set_line_width(cr, 1.0);
1077 	cairo_translate(cr, allocation.x + side_margin,
1078 			allocation.y + top_margin);
1079 	/* paint the background */
1080 	for (row = 0; row < terminal->height; row++) {
1081 		p_row = terminal_get_row(terminal, row);
1082 		for (col = 0; col < terminal->width; col++) {
1083 			/* get the attributes for this character cell */
1084 			terminal_decode_attr(terminal, row, col, &attr);
1085 
1086 			if (attr.attr.bg == terminal->color_scheme->border)
1087 				continue;
1088 
1089 			if (is_wide(p_row[col]))
1090 				unichar_width = 2 * average_width;
1091 			else
1092 				unichar_width = average_width;
1093 
1094 			terminal_set_color(terminal, cr, attr.attr.bg);
1095 			cairo_move_to(cr, col * average_width,
1096 				      row * extents.height);
1097 			cairo_rel_line_to(cr, unichar_width, 0);
1098 			cairo_rel_line_to(cr, 0, extents.height);
1099 			cairo_rel_line_to(cr, -unichar_width, 0);
1100 			cairo_close_path(cr);
1101 			cairo_fill(cr);
1102 		}
1103 	}
1104 
1105 	cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
1106 
1107 	/* paint the foreground */
1108 	glyph_run_init(&run, terminal, cr);
1109 	for (row = 0; row < terminal->height; row++) {
1110 		p_row = terminal_get_row(terminal, row);
1111 		for (col = 0; col < terminal->width; col++) {
1112 			/* get the attributes for this character cell */
1113 			terminal_decode_attr(terminal, row, col, &attr);
1114 
1115 			glyph_run_flush(&run, attr);
1116 
1117 			text_x = col * average_width;
1118 			text_y = extents.ascent + row * extents.height;
1119 			if (attr.attr.a & ATTRMASK_UNDERLINE) {
1120 				terminal_set_color(terminal, cr, attr.attr.fg);
1121 				cairo_move_to(cr, text_x, (double)text_y + 1.5);
1122 				cairo_line_to(cr, text_x + average_width, (double) text_y + 1.5);
1123 				cairo_stroke(cr);
1124 			}
1125 
1126                         /* skip space glyph (RLE) we use as a placeholder of
1127                            the right half of a double-width character,
1128                            because RLE is not available in every font. */
1129 			if (p_row[col].ch == 0x200B)
1130 				continue;
1131 
1132 			glyph_run_add(&run, text_x, text_y, &p_row[col]);
1133 		}
1134 	}
1135 
1136 	attr.key = ~0;
1137 	glyph_run_flush(&run, attr);
1138 
1139 	if ((terminal->mode & MODE_SHOW_CURSOR) &&
1140 	    !window_has_focus(terminal->window)) {
1141 		d = 0.5;
1142 
1143 		cairo_set_line_width(cr, 1);
1144 		cairo_move_to(cr, terminal->column * average_width + d,
1145 			      terminal->row * extents.height + d);
1146 		cairo_rel_line_to(cr, average_width - 2 * d, 0);
1147 		cairo_rel_line_to(cr, 0, extents.height - 2 * d);
1148 		cairo_rel_line_to(cr, -average_width + 2 * d, 0);
1149 		cairo_close_path(cr);
1150 
1151 		cairo_stroke(cr);
1152 	}
1153 
1154 	cairo_pop_group_to_source(cr);
1155 	cairo_paint(cr);
1156 	cairo_destroy(cr);
1157 	cairo_surface_destroy(surface);
1158 
1159 	if (terminal->send_cursor_position) {
1160 		cursor_x = side_margin + allocation.x +
1161 				terminal->column * average_width;
1162 		cursor_y = top_margin + allocation.y +
1163 				terminal->row * extents.height;
1164 		window_set_text_cursor_position(terminal->window,
1165 						cursor_x, cursor_y);
1166 		terminal->send_cursor_position = 0;
1167 	}
1168 }
1169 
1170 static void
terminal_write(struct terminal * terminal,const char * data,size_t length)1171 terminal_write(struct terminal *terminal, const char *data, size_t length)
1172 {
1173 	if (write(terminal->master, data, length) < 0)
1174 		abort();
1175 	terminal->send_cursor_position = 1;
1176 }
1177 
1178 static void
1179 terminal_data(struct terminal *terminal, const char *data, size_t length);
1180 
1181 static void
1182 handle_char(struct terminal *terminal, union utf8_char utf8);
1183 
1184 static void
1185 handle_sgr(struct terminal *terminal, int code);
1186 
1187 static void
handle_term_parameter(struct terminal * terminal,int code,int sr)1188 handle_term_parameter(struct terminal *terminal, int code, int sr)
1189 {
1190 	int i;
1191 
1192 	if (terminal->escape_flags & ESC_FLAG_WHAT) {
1193 		switch(code) {
1194 		case 1:  /* DECCKM */
1195 			if (sr)	terminal->key_mode = KM_APPLICATION;
1196 			else	terminal->key_mode = KM_NORMAL;
1197 			break;
1198 		case 2:  /* DECANM */
1199 			/* No VT52 support yet */
1200 			terminal->g0 = CS_US;
1201 			terminal->g1 = CS_US;
1202 			terminal->cs = terminal->g0;
1203 			break;
1204 		case 3:  /* DECCOLM */
1205 			if (sr)
1206 				terminal_resize(terminal, 132, 24);
1207 			else
1208 				terminal_resize(terminal, 80, 24);
1209 
1210 			/* set columns, but also home cursor and clear screen */
1211 			terminal->row = 0; terminal->column = 0;
1212 			for (i = 0; i < terminal->height; i++) {
1213 				memset(terminal_get_row(terminal, i),
1214 				    0, terminal->data_pitch);
1215 				attr_init(terminal_get_attr_row(terminal, i),
1216 				    terminal->curr_attr, terminal->width);
1217 			}
1218 			break;
1219 		case 5:  /* DECSCNM */
1220 			if (sr)	terminal->mode |=  MODE_INVERSE;
1221 			else	terminal->mode &= ~MODE_INVERSE;
1222 			break;
1223 		case 6:  /* DECOM */
1224 			terminal->origin_mode = sr;
1225 			if (terminal->origin_mode)
1226 				terminal->row = terminal->margin_top;
1227 			else
1228 				terminal->row = 0;
1229 			terminal->column = 0;
1230 			break;
1231 		case 7:  /* DECAWM */
1232 			if (sr)	terminal->mode |=  MODE_AUTOWRAP;
1233 			else	terminal->mode &= ~MODE_AUTOWRAP;
1234 			break;
1235 		case 8:  /* DECARM */
1236 			if (sr)	terminal->mode |=  MODE_AUTOREPEAT;
1237 			else	terminal->mode &= ~MODE_AUTOREPEAT;
1238 			break;
1239 		case 12:  /* Very visible cursor (CVVIS) */
1240 			/* FIXME: What do we do here. */
1241 			break;
1242 		case 25:
1243 			if (sr)	terminal->mode |=  MODE_SHOW_CURSOR;
1244 			else	terminal->mode &= ~MODE_SHOW_CURSOR;
1245 			break;
1246 		case 1034:   /* smm/rmm, meta mode on/off */
1247 			/* ignore */
1248 			break;
1249 		case 1037:   /* deleteSendsDel */
1250 			if (sr)	terminal->mode |=  MODE_DELETE_SENDS_DEL;
1251 			else	terminal->mode &= ~MODE_DELETE_SENDS_DEL;
1252 			break;
1253 		case 1039:   /* altSendsEscape */
1254 			if (sr)	terminal->mode |=  MODE_ALT_SENDS_ESC;
1255 			else	terminal->mode &= ~MODE_ALT_SENDS_ESC;
1256 			break;
1257 		case 1049:   /* rmcup/smcup, alternate screen */
1258 			/* Ignore.  Should be possible to implement,
1259 			 * but it's kind of annoying. */
1260 			break;
1261 		default:
1262 			fprintf(stderr, "Unknown parameter: ?%d\n", code);
1263 			break;
1264 		}
1265 	} else {
1266 		switch(code) {
1267 		case 4:  /* IRM */
1268 			if (sr)	terminal->mode |=  MODE_IRM;
1269 			else	terminal->mode &= ~MODE_IRM;
1270 			break;
1271 		case 20: /* LNM */
1272 			if (sr)	terminal->mode |=  MODE_LF_NEWLINE;
1273 			else	terminal->mode &= ~MODE_LF_NEWLINE;
1274 			break;
1275 		default:
1276 			fprintf(stderr, "Unknown parameter: %d\n", code);
1277 			break;
1278 		}
1279 	}
1280 }
1281 
1282 static void
handle_dcs(struct terminal * terminal)1283 handle_dcs(struct terminal *terminal)
1284 {
1285 }
1286 
1287 static void
handle_osc(struct terminal * terminal)1288 handle_osc(struct terminal *terminal)
1289 {
1290 	char *p;
1291 	int code;
1292 
1293 	terminal->escape[terminal->escape_length++] = '\0';
1294 	p = &terminal->escape[2];
1295 	code = strtol(p, &p, 10);
1296 	if (*p == ';') p++;
1297 
1298 	switch (code) {
1299 	case 0: /* Icon name and window title */
1300 	case 1: /* Icon label */
1301 	case 2: /* Window title*/
1302 		free(terminal->title);
1303 		terminal->title = strdup(p);
1304 		window_set_title(terminal->window, p);
1305 		break;
1306 	case 7: /* shell cwd as uri */
1307 		break;
1308 	default:
1309 		fprintf(stderr, "Unknown OSC escape code %d, text %s\n",
1310 			code, p);
1311 		break;
1312 	}
1313 }
1314 
1315 static void
handle_escape(struct terminal * terminal)1316 handle_escape(struct terminal *terminal)
1317 {
1318 	union utf8_char *row;
1319 	struct attr *attr_row;
1320 	char *p;
1321 	int i, count, x, y, top, bottom;
1322 	int args[10], set[10] = { 0, };
1323 	char response[MAX_RESPONSE] = {0, };
1324 	struct rectangle allocation;
1325 
1326 	terminal->escape[terminal->escape_length++] = '\0';
1327 	i = 0;
1328 	p = &terminal->escape[2];
1329 	while ((isdigit(*p) || *p == ';') && i < 10) {
1330 		if (*p == ';') {
1331 			if (!set[i]) {
1332 				args[i] = 0;
1333 				set[i] = 1;
1334 			}
1335 			p++;
1336 			i++;
1337 		} else {
1338 			args[i] = strtol(p, &p, 10);
1339 			set[i] = 1;
1340 		}
1341 	}
1342 
1343 	switch (*p) {
1344 	case '@':    /* ICH */
1345 		count = set[0] ? args[0] : 1;
1346 		if (count == 0) count = 1;
1347 		terminal_shift_line(terminal, count);
1348 		break;
1349 	case 'A':    /* CUU */
1350 		count = set[0] ? args[0] : 1;
1351 		if (count == 0) count = 1;
1352 		if (terminal->row - count >= terminal->margin_top)
1353 			terminal->row -= count;
1354 		else
1355 			terminal->row = terminal->margin_top;
1356 		break;
1357 	case 'B':    /* CUD */
1358 		count = set[0] ? args[0] : 1;
1359 		if (count == 0) count = 1;
1360 		if (terminal->row + count <= terminal->margin_bottom)
1361 			terminal->row += count;
1362 		else
1363 			terminal->row = terminal->margin_bottom;
1364 		break;
1365 	case 'C':    /* CUF */
1366 		count = set[0] ? args[0] : 1;
1367 		if (count == 0) count = 1;
1368 		if ((terminal->column + count) < terminal->width)
1369 			terminal->column += count;
1370 		else
1371 			terminal->column = terminal->width - 1;
1372 		break;
1373 	case 'D':    /* CUB */
1374 		count = set[0] ? args[0] : 1;
1375 		if (count == 0) count = 1;
1376 		if ((terminal->column - count) >= 0)
1377 			terminal->column -= count;
1378 		else
1379 			terminal->column = 0;
1380 		break;
1381 	case 'E':    /* CNL */
1382 		count = set[0] ? args[0] : 1;
1383 		if (terminal->row + count <= terminal->margin_bottom)
1384 			terminal->row += count;
1385 		else
1386 			terminal->row = terminal->margin_bottom;
1387 		terminal->column = 0;
1388 		break;
1389 	case 'F':    /* CPL */
1390 		count = set[0] ? args[0] : 1;
1391 		if (terminal->row - count >= terminal->margin_top)
1392 			terminal->row -= count;
1393 		else
1394 			terminal->row = terminal->margin_top;
1395 		terminal->column = 0;
1396 		break;
1397 	case 'G':    /* CHA */
1398 		y = set[0] ? args[0] : 1;
1399 		y = y <= 0 ? 1 : y > terminal->width ? terminal->width : y;
1400 
1401 		terminal->column = y - 1;
1402 		break;
1403 	case 'f':    /* HVP */
1404 	case 'H':    /* CUP */
1405 		x = (set[1] ? args[1] : 1) - 1;
1406 		x = x < 0 ? 0 :
1407 		    (x >= terminal->width ? terminal->width - 1 : x);
1408 
1409 		y = (set[0] ? args[0] : 1) - 1;
1410 		if (terminal->origin_mode) {
1411 			y += terminal->margin_top;
1412 			y = y < terminal->margin_top ? terminal->margin_top :
1413 			    (y > terminal->margin_bottom ? terminal->margin_bottom : y);
1414 		} else {
1415 			y = y < 0 ? 0 :
1416 			    (y >= terminal->height ? terminal->height - 1 : y);
1417 		}
1418 
1419 		terminal->row = y;
1420 		terminal->column = x;
1421 		break;
1422 	case 'I':    /* CHT */
1423 		count = set[0] ? args[0] : 1;
1424 		if (count == 0) count = 1;
1425 		while (count > 0 && terminal->column < terminal->width) {
1426 			if (terminal->tab_ruler[terminal->column]) count--;
1427 			terminal->column++;
1428 		}
1429 		terminal->column--;
1430 		break;
1431 	case 'J':    /* ED */
1432 		row = terminal_get_row(terminal, terminal->row);
1433 		attr_row = terminal_get_attr_row(terminal, terminal->row);
1434 		if (!set[0] || args[0] == 0 || args[0] > 2) {
1435 			memset(&row[terminal->column],
1436 			       0, (terminal->width - terminal->column) * sizeof(union utf8_char));
1437 			attr_init(&attr_row[terminal->column],
1438 			       terminal->curr_attr, terminal->width - terminal->column);
1439 			for (i = terminal->row + 1; i < terminal->height; i++) {
1440 				memset(terminal_get_row(terminal, i),
1441 				    0, terminal->data_pitch);
1442 				attr_init(terminal_get_attr_row(terminal, i),
1443 				    terminal->curr_attr, terminal->width);
1444 			}
1445 		} else if (args[0] == 1) {
1446 			memset(row, 0, (terminal->column+1) * sizeof(union utf8_char));
1447 			attr_init(attr_row, terminal->curr_attr, terminal->column+1);
1448 			for (i = 0; i < terminal->row; i++) {
1449 				memset(terminal_get_row(terminal, i),
1450 				    0, terminal->data_pitch);
1451 				attr_init(terminal_get_attr_row(terminal, i),
1452 				    terminal->curr_attr, terminal->width);
1453 			}
1454 		} else if (args[0] == 2) {
1455 			/* Clear screen by scrolling contents out */
1456 			terminal_scroll_buffer(terminal,
1457 					       terminal->end - terminal->start);
1458 		}
1459 		break;
1460 	case 'K':    /* EL */
1461 		row = terminal_get_row(terminal, terminal->row);
1462 		attr_row = terminal_get_attr_row(terminal, terminal->row);
1463 		if (!set[0] || args[0] == 0 || args[0] > 2) {
1464 			memset(&row[terminal->column], 0,
1465 			    (terminal->width - terminal->column) * sizeof(union utf8_char));
1466 			attr_init(&attr_row[terminal->column], terminal->curr_attr,
1467 			    terminal->width - terminal->column);
1468 		} else if (args[0] == 1) {
1469 			memset(row, 0, (terminal->column+1) * sizeof(union utf8_char));
1470 			attr_init(attr_row, terminal->curr_attr, terminal->column+1);
1471 		} else if (args[0] == 2) {
1472 			memset(row, 0, terminal->data_pitch);
1473 			attr_init(attr_row, terminal->curr_attr, terminal->width);
1474 		}
1475 		break;
1476 	case 'L':    /* IL */
1477 		count = set[0] ? args[0] : 1;
1478 		if (count == 0) count = 1;
1479 		if (terminal->row >= terminal->margin_top &&
1480 			terminal->row < terminal->margin_bottom)
1481 		{
1482 			top = terminal->margin_top;
1483 			terminal->margin_top = terminal->row;
1484 			terminal_scroll(terminal, 0 - count);
1485 			terminal->margin_top = top;
1486 		} else if (terminal->row == terminal->margin_bottom) {
1487 			memset(terminal_get_row(terminal, terminal->row),
1488 			       0, terminal->data_pitch);
1489 			attr_init(terminal_get_attr_row(terminal, terminal->row),
1490 				terminal->curr_attr, terminal->width);
1491 		}
1492 		break;
1493 	case 'M':    /* DL */
1494 		count = set[0] ? args[0] : 1;
1495 		if (count == 0) count = 1;
1496 		if (terminal->row >= terminal->margin_top &&
1497 			terminal->row < terminal->margin_bottom)
1498 		{
1499 			top = terminal->margin_top;
1500 			terminal->margin_top = terminal->row;
1501 			terminal_scroll(terminal, count);
1502 			terminal->margin_top = top;
1503 		} else if (terminal->row == terminal->margin_bottom) {
1504 			memset(terminal_get_row(terminal, terminal->row),
1505 			       0, terminal->data_pitch);
1506 		}
1507 		break;
1508 	case 'P':    /* DCH */
1509 		count = set[0] ? args[0] : 1;
1510 		if (count == 0) count = 1;
1511 		terminal_shift_line(terminal, 0 - count);
1512 		break;
1513 	case 'S':    /* SU */
1514 		terminal_scroll(terminal, set[0] ? args[0] : 1);
1515 		break;
1516 	case 'T':    /* SD */
1517 		terminal_scroll(terminal, 0 - (set[0] ? args[0] : 1));
1518 		break;
1519 	case 'X':    /* ECH */
1520 		count = set[0] ? args[0] : 1;
1521 		if (count == 0) count = 1;
1522 		if ((terminal->column + count) > terminal->width)
1523 			count = terminal->width - terminal->column;
1524 		row = terminal_get_row(terminal, terminal->row);
1525 		attr_row = terminal_get_attr_row(terminal, terminal->row);
1526 		memset(&row[terminal->column], 0, count * sizeof(union utf8_char));
1527 		attr_init(&attr_row[terminal->column], terminal->curr_attr, count);
1528 		break;
1529 	case 'Z':    /* CBT */
1530 		count = set[0] ? args[0] : 1;
1531 		if (count == 0) count = 1;
1532 		while (count > 0 && terminal->column >= 0) {
1533 			if (terminal->tab_ruler[terminal->column]) count--;
1534 			terminal->column--;
1535 		}
1536 		terminal->column++;
1537 		break;
1538 	case '`':    /* HPA */
1539 		y = set[0] ? args[0] : 1;
1540 		y = y <= 0 ? 1 : y > terminal->width ? terminal->width : y;
1541 
1542 		terminal->column = y - 1;
1543 		break;
1544 	case 'b':    /* REP */
1545 		count = set[0] ? args[0] : 1;
1546 		if (count == 0) count = 1;
1547 		if (terminal->last_char.byte[0])
1548 			for (i = 0; i < count; i++)
1549 				handle_char(terminal, terminal->last_char);
1550 		terminal->last_char.byte[0] = 0;
1551 		break;
1552 	case 'c':    /* Primary DA */
1553 		terminal_write(terminal, "\e[?6c", 5);
1554 		break;
1555 	case 'd':    /* VPA */
1556 		x = set[0] ? args[0] : 1;
1557 		x = x <= 0 ? 1 : x > terminal->height ? terminal->height : x;
1558 
1559 		terminal->row = x - 1;
1560 		break;
1561 	case 'g':    /* TBC */
1562 		if (!set[0] || args[0] == 0) {
1563 			terminal->tab_ruler[terminal->column] = 0;
1564 		} else if (args[0] == 3) {
1565 			memset(terminal->tab_ruler, 0, terminal->width);
1566 		}
1567 		break;
1568 	case 'h':    /* SM */
1569 		for (i = 0; i < 10 && set[i]; i++) {
1570 			handle_term_parameter(terminal, args[i], 1);
1571 		}
1572 		break;
1573 	case 'l':    /* RM */
1574 		for (i = 0; i < 10 && set[i]; i++) {
1575 			handle_term_parameter(terminal, args[i], 0);
1576 		}
1577 		break;
1578 	case 'm':    /* SGR */
1579 		for (i = 0; i < 10; i++) {
1580 			if (i <= 7 && set[i] && set[i + 1] &&
1581 				set[i + 2] && args[i + 1] == 5)
1582 			{
1583 				if (args[i] == 38) {
1584 					handle_sgr(terminal, args[i + 2] + 256);
1585 					break;
1586 				} else if (args[i] == 48) {
1587 					handle_sgr(terminal, args[i + 2] + 512);
1588 					break;
1589 				}
1590 			}
1591 			if (set[i]) {
1592 				handle_sgr(terminal, args[i]);
1593 			} else if (i == 0) {
1594 				handle_sgr(terminal, 0);
1595 				break;
1596 			} else {
1597 				break;
1598 			}
1599 		}
1600 		break;
1601 	case 'n':    /* DSR */
1602 		i = set[0] ? args[0] : 0;
1603 		if (i == 0 || i == 5) {
1604 			terminal_write(terminal, "\e[0n", 4);
1605 		} else if (i == 6) {
1606 			snprintf(response, MAX_RESPONSE, "\e[%d;%dR",
1607 			         terminal->origin_mode ?
1608 				     terminal->row+terminal->margin_top : terminal->row+1,
1609 				 terminal->column+1);
1610 			terminal_write(terminal, response, strlen(response));
1611 		}
1612  		break;
1613 	case 'r':
1614 		if (!set[0]) {
1615 			terminal->margin_top = 0;
1616 			terminal->margin_bottom = terminal->height-1;
1617 			terminal->row = 0;
1618 			terminal->column = 0;
1619 		} else {
1620 			top = (set[0] ? args[0] : 1) - 1;
1621 			top = top < 0 ? 0 :
1622 			      (top >= terminal->height ? terminal->height - 1 : top);
1623 			bottom = (set[1] ? args[1] : 1) - 1;
1624 			bottom = bottom < 0 ? 0 :
1625 			         (bottom >= terminal->height ? terminal->height - 1 : bottom);
1626 			if (bottom > top) {
1627 				terminal->margin_top = top;
1628 				terminal->margin_bottom = bottom;
1629 			} else {
1630 				terminal->margin_top = 0;
1631 				terminal->margin_bottom = terminal->height-1;
1632 			}
1633 			if (terminal->origin_mode)
1634 				terminal->row = terminal->margin_top;
1635 			else
1636 				terminal->row = 0;
1637 			terminal->column = 0;
1638 		}
1639 		break;
1640 	case 's':
1641 		terminal->saved_row = terminal->row;
1642 		terminal->saved_column = terminal->column;
1643 		break;
1644 	case 't':    /* windowOps */
1645 		if (!set[0]) break;
1646 		switch (args[0]) {
1647 		case 4:  /* resize px */
1648 			if (set[1] && set[2]) {
1649 				widget_schedule_resize(terminal->widget,
1650 						       args[2], args[1]);
1651 			}
1652 			break;
1653 		case 8:  /* resize ch */
1654 			if (set[1] && set[2]) {
1655 				terminal_resize(terminal, args[2], args[1]);
1656 			}
1657 			break;
1658 		case 13: /* report position */
1659 			widget_get_allocation(terminal->widget, &allocation);
1660 			snprintf(response, MAX_RESPONSE, "\e[3;%d;%dt",
1661 				 allocation.x, allocation.y);
1662 			terminal_write(terminal, response, strlen(response));
1663 			break;
1664 		case 14: /* report px */
1665 			widget_get_allocation(terminal->widget, &allocation);
1666 			snprintf(response, MAX_RESPONSE, "\e[4;%d;%dt",
1667 				 allocation.height, allocation.width);
1668 			terminal_write(terminal, response, strlen(response));
1669 			break;
1670 		case 18: /* report ch */
1671 			snprintf(response, MAX_RESPONSE, "\e[9;%d;%dt",
1672 				 terminal->height, terminal->width);
1673 			terminal_write(terminal, response, strlen(response));
1674 			break;
1675 		case 21: /* report title */
1676 			snprintf(response, MAX_RESPONSE, "\e]l%s\e\\",
1677 				 window_get_title(terminal->window));
1678 			terminal_write(terminal, response, strlen(response));
1679 			break;
1680 		default:
1681 			if (args[0] >= 24)
1682 				terminal_resize(terminal, terminal->width, args[0]);
1683 			else
1684 				fprintf(stderr, "Unimplemented windowOp %d\n", args[0]);
1685 			break;
1686 		}
1687 	case 'u':
1688 		terminal->row = terminal->saved_row;
1689 		terminal->column = terminal->saved_column;
1690 		break;
1691 	default:
1692 		fprintf(stderr, "Unknown CSI escape: %c\n", *p);
1693 		break;
1694 	}
1695 }
1696 
1697 static void
handle_non_csi_escape(struct terminal * terminal,char code)1698 handle_non_csi_escape(struct terminal *terminal, char code)
1699 {
1700 	switch(code) {
1701 	case 'M':    /* RI */
1702 		terminal->row -= 1;
1703 		if (terminal->row < terminal->margin_top) {
1704 			terminal->row = terminal->margin_top;
1705 			terminal_scroll(terminal, -1);
1706 		}
1707 		break;
1708 	case 'E':    /* NEL */
1709 		terminal->column = 0;
1710 		// fallthrough
1711 	case 'D':    /* IND */
1712 		terminal->row += 1;
1713 		if (terminal->row > terminal->margin_bottom) {
1714 			terminal->row = terminal->margin_bottom;
1715 			terminal_scroll(terminal, +1);
1716 		}
1717 		break;
1718 	case 'c':    /* RIS */
1719 		terminal_init(terminal);
1720 		break;
1721 	case 'H':    /* HTS */
1722 		terminal->tab_ruler[terminal->column] = 1;
1723 		break;
1724 	case '7':    /* DECSC */
1725 		terminal->saved_row = terminal->row;
1726 		terminal->saved_column = terminal->column;
1727 		terminal->saved_attr = terminal->curr_attr;
1728 		terminal->saved_origin_mode = terminal->origin_mode;
1729 		terminal->saved_cs = terminal->cs;
1730 		terminal->saved_g0 = terminal->g0;
1731 		terminal->saved_g1 = terminal->g1;
1732 		break;
1733 	case '8':    /* DECRC */
1734 		terminal->row = terminal->saved_row;
1735 		terminal->column = terminal->saved_column;
1736 		terminal->curr_attr = terminal->saved_attr;
1737 		terminal->origin_mode = terminal->saved_origin_mode;
1738 		terminal->cs = terminal->saved_cs;
1739 		terminal->g0 = terminal->saved_g0;
1740 		terminal->g1 = terminal->saved_g1;
1741 		break;
1742 	case '=':    /* DECPAM */
1743 		terminal->key_mode = KM_APPLICATION;
1744 		break;
1745 	case '>':    /* DECPNM */
1746 		terminal->key_mode = KM_NORMAL;
1747 		break;
1748 	default:
1749 		fprintf(stderr, "Unknown escape code: %c\n", code);
1750 		break;
1751 	}
1752 }
1753 
1754 static void
handle_special_escape(struct terminal * terminal,char special,char code)1755 handle_special_escape(struct terminal *terminal, char special, char code)
1756 {
1757 	int i, numChars;
1758 
1759 	if (special == '#') {
1760 		switch(code) {
1761 		case '8':
1762 			/* fill with 'E', no cheap way to do this */
1763 			memset(terminal->data, 0, terminal->data_pitch * terminal->height);
1764 			numChars = terminal->width * terminal->height;
1765 			for (i = 0; i < numChars; i++) {
1766 				terminal->data[i].byte[0] = 'E';
1767 			}
1768 			break;
1769 		default:
1770 			fprintf(stderr, "Unknown HASH escape #%c\n", code);
1771 			break;
1772 		}
1773 	} else if (special == '(' || special == ')') {
1774 		switch(code) {
1775 		case '0':
1776 			if (special == '(')
1777 				terminal->g0 = CS_SPECIAL;
1778 			else
1779 				terminal->g1 = CS_SPECIAL;
1780 			break;
1781 		case 'A':
1782 			if (special == '(')
1783 				terminal->g0 = CS_UK;
1784 			else
1785 				terminal->g1 = CS_UK;
1786 			break;
1787 		case 'B':
1788 			if (special == '(')
1789 				terminal->g0 = CS_US;
1790 			else
1791 				terminal->g1 = CS_US;
1792 			break;
1793 		default:
1794 			fprintf(stderr, "Unknown character set %c\n", code);
1795 			break;
1796 		}
1797 	} else {
1798 		fprintf(stderr, "Unknown special escape %c%c\n", special, code);
1799 	}
1800 }
1801 
1802 static void
handle_sgr(struct terminal * terminal,int code)1803 handle_sgr(struct terminal *terminal, int code)
1804 {
1805 	switch(code) {
1806 	case 0:
1807 		terminal->curr_attr = terminal->color_scheme->default_attr;
1808 		break;
1809 	case 1:
1810 		terminal->curr_attr.a |= ATTRMASK_BOLD;
1811 		if (terminal->curr_attr.fg < 8)
1812 			terminal->curr_attr.fg += 8;
1813 		break;
1814 	case 4:
1815 		terminal->curr_attr.a |= ATTRMASK_UNDERLINE;
1816 		break;
1817 	case 5:
1818 		terminal->curr_attr.a |= ATTRMASK_BLINK;
1819 		break;
1820 	case 8:
1821 		terminal->curr_attr.a |= ATTRMASK_CONCEALED;
1822 		break;
1823 	case 2:
1824 	case 21:
1825 	case 22:
1826 		terminal->curr_attr.a &= ~ATTRMASK_BOLD;
1827 		if (terminal->curr_attr.fg < 16 && terminal->curr_attr.fg >= 8)
1828 			terminal->curr_attr.fg -= 8;
1829 		break;
1830 	case 24:
1831 		terminal->curr_attr.a &= ~ATTRMASK_UNDERLINE;
1832 		break;
1833 	case 25:
1834 		terminal->curr_attr.a &= ~ATTRMASK_BLINK;
1835 		break;
1836 	case 7:
1837 	case 26:
1838 		terminal->curr_attr.a |= ATTRMASK_INVERSE;
1839 		break;
1840 	case 27:
1841 		terminal->curr_attr.a &= ~ATTRMASK_INVERSE;
1842 		break;
1843 	case 28:
1844 		terminal->curr_attr.a &= ~ATTRMASK_CONCEALED;
1845 		break;
1846 	case 39:
1847 		terminal->curr_attr.fg = terminal->color_scheme->default_attr.fg;
1848 		break;
1849 	case 49:
1850 		terminal->curr_attr.bg = terminal->color_scheme->default_attr.bg;
1851 		break;
1852 	default:
1853 		if (code >= 30 && code <= 37) {
1854 			terminal->curr_attr.fg = code - 30;
1855 			if (terminal->curr_attr.a & ATTRMASK_BOLD)
1856 				terminal->curr_attr.fg += 8;
1857 		} else if (code >= 40 && code <= 47) {
1858 			terminal->curr_attr.bg = code - 40;
1859 		} else if (code >= 90 && code <= 97) {
1860 			terminal->curr_attr.fg = code - 90 + 8;
1861 		} else if (code >= 100 && code <= 107) {
1862 			terminal->curr_attr.bg = code - 100 + 8;
1863 		} else if (code >= 256 && code < 512) {
1864 			terminal->curr_attr.fg = code - 256;
1865 		} else if (code >= 512 && code < 768) {
1866 			terminal->curr_attr.bg = code - 512;
1867 		} else {
1868 			fprintf(stderr, "Unknown SGR code: %d\n", code);
1869 		}
1870 		break;
1871 	}
1872 }
1873 
1874 /* Returns 1 if c was special, otherwise 0 */
1875 static int
handle_special_char(struct terminal * terminal,char c)1876 handle_special_char(struct terminal *terminal, char c)
1877 {
1878 	union utf8_char *row;
1879 	struct attr *attr_row;
1880 
1881 	row = terminal_get_row(terminal, terminal->row);
1882 	attr_row = terminal_get_attr_row(terminal, terminal->row);
1883 
1884 	switch(c) {
1885 	case '\r':
1886 		terminal->column = 0;
1887 		break;
1888 	case '\n':
1889 		if (terminal->mode & MODE_LF_NEWLINE) {
1890 			terminal->column = 0;
1891 		}
1892 		/* fallthrough */
1893 	case '\v':
1894 	case '\f':
1895 		terminal->row++;
1896 		if (terminal->row > terminal->margin_bottom) {
1897 			terminal->row = terminal->margin_bottom;
1898 			terminal_scroll(terminal, +1);
1899 		}
1900 
1901 		break;
1902 	case '\t':
1903 		while (terminal->column < terminal->width) {
1904 			if (terminal->mode & MODE_IRM)
1905 				terminal_shift_line(terminal, +1);
1906 
1907 			if (row[terminal->column].byte[0] == '\0') {
1908 				row[terminal->column].byte[0] = ' ';
1909 				row[terminal->column].byte[1] = '\0';
1910 				attr_row[terminal->column] = terminal->curr_attr;
1911 			}
1912 
1913 			terminal->column++;
1914 			if (terminal->tab_ruler[terminal->column]) break;
1915 		}
1916 		if (terminal->column >= terminal->width) {
1917 			terminal->column = terminal->width - 1;
1918 		}
1919 
1920 		break;
1921 	case '\b':
1922 		if (terminal->column >= terminal->width) {
1923 			terminal->column = terminal->width - 2;
1924 		} else if (terminal->column > 0) {
1925 			terminal->column--;
1926 		} else if (terminal->mode & MODE_AUTOWRAP) {
1927 			terminal->column = terminal->width - 1;
1928 			terminal->row -= 1;
1929 			if (terminal->row < terminal->margin_top) {
1930 				terminal->row = terminal->margin_top;
1931 				terminal_scroll(terminal, -1);
1932 			}
1933 		}
1934 
1935 		break;
1936 	case '\a':
1937 		/* Bell */
1938 		break;
1939 	case '\x0E': /* SO */
1940 		terminal->cs = terminal->g1;
1941 		break;
1942 	case '\x0F': /* SI */
1943 		terminal->cs = terminal->g0;
1944 		break;
1945 	case '\0':
1946 		break;
1947 	default:
1948 		return 0;
1949 	}
1950 
1951 	return 1;
1952 }
1953 
1954 static void
handle_char(struct terminal * terminal,union utf8_char utf8)1955 handle_char(struct terminal *terminal, union utf8_char utf8)
1956 {
1957 	union utf8_char *row;
1958 	struct attr *attr_row;
1959 
1960 	if (handle_special_char(terminal, utf8.byte[0])) return;
1961 
1962 	apply_char_set(terminal->cs, &utf8);
1963 
1964 	/* There are a whole lot of non-characters, control codes,
1965 	 * and formatting codes that should probably be ignored,
1966 	 * for example: */
1967 	if (strncmp((char*) utf8.byte, "\xEF\xBB\xBF", 3) == 0) {
1968 		/* BOM, ignore */
1969 		return;
1970 	}
1971 
1972 	/* Some of these non-characters should be translated, e.g.: */
1973 	if (utf8.byte[0] < 32) {
1974 		utf8.byte[0] = utf8.byte[0] + 64;
1975 	}
1976 
1977 	/* handle right margin effects */
1978 	if (terminal->column >= terminal->width) {
1979 		if (terminal->mode & MODE_AUTOWRAP) {
1980 			terminal->column = 0;
1981 			terminal->row += 1;
1982 			if (terminal->row > terminal->margin_bottom) {
1983 				terminal->row = terminal->margin_bottom;
1984 				terminal_scroll(terminal, +1);
1985 			}
1986 		} else {
1987 			terminal->column--;
1988  		}
1989  	}
1990 
1991 	row = terminal_get_row(terminal, terminal->row);
1992 	attr_row = terminal_get_attr_row(terminal, terminal->row);
1993 
1994 	if (terminal->mode & MODE_IRM)
1995 		terminal_shift_line(terminal, +1);
1996 	row[terminal->column] = utf8;
1997 	attr_row[terminal->column++] = terminal->curr_attr;
1998 
1999 	if (terminal->row + terminal->start + 1 > terminal->end)
2000 		terminal->end = terminal->row + terminal->start + 1;
2001 	if (terminal->end == terminal->buffer_height)
2002 		terminal->log_size = terminal->buffer_height;
2003 	else if (terminal->log_size < terminal->buffer_height)
2004 		terminal->log_size = terminal->end;
2005 
2006 	/* cursor jump for wide character. */
2007 	if (is_wide(utf8))
2008 		row[terminal->column++].ch = 0x200B; /* space glyph */
2009 
2010 	if (utf8.ch != terminal->last_char.ch)
2011 		terminal->last_char = utf8;
2012 }
2013 
2014 static void
escape_append_utf8(struct terminal * terminal,union utf8_char utf8)2015 escape_append_utf8(struct terminal *terminal, union utf8_char utf8)
2016 {
2017 	int len, i;
2018 
2019 	if ((utf8.byte[0] & 0x80) == 0x00)       len = 1;
2020 	else if ((utf8.byte[0] & 0xE0) == 0xC0)  len = 2;
2021 	else if ((utf8.byte[0] & 0xF0) == 0xE0)  len = 3;
2022 	else if ((utf8.byte[0] & 0xF8) == 0xF0)  len = 4;
2023 	else                                     len = 1;  /* Invalid, cannot happen */
2024 
2025 	if (terminal->escape_length + len <= MAX_ESCAPE) {
2026 		for (i = 0; i < len; i++)
2027 			terminal->escape[terminal->escape_length + i] = utf8.byte[i];
2028 		terminal->escape_length += len;
2029 	} else if (terminal->escape_length < MAX_ESCAPE) {
2030 		terminal->escape[terminal->escape_length++] = 0;
2031 	}
2032 }
2033 
2034 static void
terminal_data(struct terminal * terminal,const char * data,size_t length)2035 terminal_data(struct terminal *terminal, const char *data, size_t length)
2036 {
2037 	unsigned int i;
2038 	union utf8_char utf8;
2039 	enum utf8_state parser_state;
2040 
2041 	for (i = 0; i < length; i++) {
2042 		parser_state =
2043 			utf8_next_char(&terminal->state_machine, data[i]);
2044 		switch(parser_state) {
2045 		case utf8state_accept:
2046 			utf8.ch = terminal->state_machine.s.ch;
2047 			break;
2048 		case utf8state_reject:
2049 			/* the unicode replacement character */
2050 			utf8.byte[0] = 0xEF;
2051 			utf8.byte[1] = 0xBF;
2052 			utf8.byte[2] = 0xBD;
2053 			utf8.byte[3] = 0x00;
2054 			break;
2055 		default:
2056 			continue;
2057 		}
2058 
2059 		/* assume escape codes never use non-ASCII characters */
2060 		switch (terminal->state) {
2061 		case escape_state_escape:
2062 			escape_append_utf8(terminal, utf8);
2063 			switch (utf8.byte[0]) {
2064 			case 'P':  /* DCS */
2065 				terminal->state = escape_state_dcs;
2066 				break;
2067 			case '[':  /* CSI */
2068 				terminal->state = escape_state_csi;
2069 				break;
2070 			case ']':  /* OSC */
2071 				terminal->state = escape_state_osc;
2072 				break;
2073 			case '#':
2074 			case '(':
2075 			case ')':  /* special */
2076 				terminal->state = escape_state_special;
2077 				break;
2078 			case '^':  /* PM (not implemented) */
2079 			case '_':  /* APC (not implemented) */
2080 				terminal->state = escape_state_ignore;
2081 				break;
2082 			default:
2083 				terminal->state = escape_state_normal;
2084 				handle_non_csi_escape(terminal, utf8.byte[0]);
2085 				break;
2086 			}
2087 			continue;
2088 		case escape_state_csi:
2089 			if (handle_special_char(terminal, utf8.byte[0]) != 0) {
2090 				/* do nothing */
2091 			} else if (utf8.byte[0] == '?') {
2092 				terminal->escape_flags |= ESC_FLAG_WHAT;
2093 			} else if (utf8.byte[0] == '>') {
2094 				terminal->escape_flags |= ESC_FLAG_GT;
2095 			} else if (utf8.byte[0] == '!') {
2096 				terminal->escape_flags |= ESC_FLAG_BANG;
2097 			} else if (utf8.byte[0] == '$') {
2098 				terminal->escape_flags |= ESC_FLAG_CASH;
2099 			} else if (utf8.byte[0] == '\'') {
2100 				terminal->escape_flags |= ESC_FLAG_SQUOTE;
2101 			} else if (utf8.byte[0] == '"') {
2102 				terminal->escape_flags |= ESC_FLAG_DQUOTE;
2103 			} else if (utf8.byte[0] == ' ') {
2104 				terminal->escape_flags |= ESC_FLAG_SPACE;
2105 			} else {
2106 				escape_append_utf8(terminal, utf8);
2107 				if (terminal->escape_length >= MAX_ESCAPE)
2108 					terminal->state = escape_state_normal;
2109 			}
2110 
2111 			if (isalpha(utf8.byte[0]) || utf8.byte[0] == '@' ||
2112 				utf8.byte[0] == '`')
2113 			{
2114 				terminal->state = escape_state_normal;
2115 				handle_escape(terminal);
2116 			} else {
2117 			}
2118 			continue;
2119 		case escape_state_inner_escape:
2120 			if (utf8.byte[0] == '\\') {
2121 				terminal->state = escape_state_normal;
2122 				if (terminal->outer_state == escape_state_dcs) {
2123 					handle_dcs(terminal);
2124 				} else if (terminal->outer_state == escape_state_osc) {
2125 					handle_osc(terminal);
2126 				}
2127 			} else if (utf8.byte[0] == '\e') {
2128 				terminal->state = terminal->outer_state;
2129 				escape_append_utf8(terminal, utf8);
2130 				if (terminal->escape_length >= MAX_ESCAPE)
2131 					terminal->state = escape_state_normal;
2132 			} else {
2133 				terminal->state = terminal->outer_state;
2134 				if (terminal->escape_length < MAX_ESCAPE)
2135 					terminal->escape[terminal->escape_length++] = '\e';
2136 				escape_append_utf8(terminal, utf8);
2137 				if (terminal->escape_length >= MAX_ESCAPE)
2138 					terminal->state = escape_state_normal;
2139 			}
2140 			continue;
2141 		case escape_state_dcs:
2142 		case escape_state_osc:
2143 		case escape_state_ignore:
2144 			if (utf8.byte[0] == '\e') {
2145 				terminal->outer_state = terminal->state;
2146 				terminal->state = escape_state_inner_escape;
2147 			} else if (utf8.byte[0] == '\a' && terminal->state == escape_state_osc) {
2148 				terminal->state = escape_state_normal;
2149 				handle_osc(terminal);
2150 			} else {
2151 				escape_append_utf8(terminal, utf8);
2152 				if (terminal->escape_length >= MAX_ESCAPE)
2153 					terminal->state = escape_state_normal;
2154 			}
2155 			continue;
2156 		case escape_state_special:
2157 			escape_append_utf8(terminal, utf8);
2158 			terminal->state = escape_state_normal;
2159 			if (isdigit(utf8.byte[0]) || isalpha(utf8.byte[0])) {
2160 				handle_special_escape(terminal, terminal->escape[1],
2161 				                      utf8.byte[0]);
2162 			}
2163 			continue;
2164 		default:
2165 			break;
2166 		}
2167 
2168 		/* this is valid, because ASCII characters are never used to
2169 		 * introduce a multibyte sequence in UTF-8 */
2170 		if (utf8.byte[0] == '\e') {
2171 			terminal->state = escape_state_escape;
2172 			terminal->outer_state = escape_state_normal;
2173 			terminal->escape[0] = '\e';
2174 			terminal->escape_length = 1;
2175 			terminal->escape_flags = 0;
2176 		} else {
2177 			handle_char(terminal, utf8);
2178 		} /* if */
2179 	} /* for */
2180 
2181 	window_schedule_redraw(terminal->window);
2182 }
2183 
2184 static void
data_source_target(void * data,struct wl_data_source * source,const char * mime_type)2185 data_source_target(void *data,
2186 		   struct wl_data_source *source, const char *mime_type)
2187 {
2188 	fprintf(stderr, "data_source_target, %s\n", mime_type);
2189 }
2190 
2191 static void
data_source_send(void * data,struct wl_data_source * source,const char * mime_type,int32_t fd)2192 data_source_send(void *data,
2193 		 struct wl_data_source *source,
2194 		 const char *mime_type, int32_t fd)
2195 {
2196 	struct terminal *terminal = data;
2197 
2198 	terminal_send_selection(terminal, fd);
2199 }
2200 
2201 static void
data_source_cancelled(void * data,struct wl_data_source * source)2202 data_source_cancelled(void *data, struct wl_data_source *source)
2203 {
2204 	wl_data_source_destroy(source);
2205 }
2206 
2207 static const struct wl_data_source_listener data_source_listener = {
2208 	data_source_target,
2209 	data_source_send,
2210 	data_source_cancelled
2211 };
2212 
2213 static const char text_mime_type[] = "text/plain;charset=utf-8";
2214 
2215 static void
data_handler(struct window * window,struct input * input,float x,float y,const char ** types,void * data)2216 data_handler(struct window *window,
2217 	     struct input *input,
2218 	     float x, float y, const char **types, void *data)
2219 {
2220 	int i, has_text = 0;
2221 
2222 	if (!types)
2223 		return;
2224 	for (i = 0; types[i]; i++)
2225 		if (strcmp(types[i], text_mime_type) == 0)
2226 			has_text = 1;
2227 
2228 	if (!has_text) {
2229 		input_accept(input, NULL);
2230 	} else {
2231 		input_accept(input, text_mime_type);
2232 	}
2233 }
2234 
2235 static void
drop_handler(struct window * window,struct input * input,int32_t x,int32_t y,void * data)2236 drop_handler(struct window *window, struct input *input,
2237 	     int32_t x, int32_t y, void *data)
2238 {
2239 	struct terminal *terminal = data;
2240 
2241 	input_receive_drag_data_to_fd(input, text_mime_type, terminal->master);
2242 }
2243 
2244 static void
fullscreen_handler(struct window * window,void * data)2245 fullscreen_handler(struct window *window, void *data)
2246 {
2247 	struct terminal *terminal = data;
2248 
2249 	window_set_fullscreen(window, !window_is_fullscreen(terminal->window));
2250 }
2251 
2252 static void
close_handler(void * data)2253 close_handler(void *data)
2254 {
2255 	struct terminal *terminal = data;
2256 
2257 	terminal_destroy(terminal);
2258 }
2259 
2260 static void
terminal_copy(struct terminal * terminal,struct input * input)2261 terminal_copy(struct terminal *terminal, struct input *input)
2262 {
2263 	terminal->selection =
2264 		display_create_data_source(terminal->display);
2265 	wl_data_source_offer(terminal->selection,
2266 			     "text/plain;charset=utf-8");
2267 	wl_data_source_add_listener(terminal->selection,
2268 				    &data_source_listener, terminal);
2269 	input_set_selection(input, terminal->selection,
2270 			    display_get_serial(terminal->display));
2271 }
2272 
2273 static void
terminal_paste(struct terminal * terminal,struct input * input)2274 terminal_paste(struct terminal *terminal, struct input *input)
2275 {
2276 	input_receive_selection_data_to_fd(input,
2277 					   "text/plain;charset=utf-8",
2278 					   terminal->master);
2279 
2280 }
2281 
2282 static void
terminal_new_instance(struct terminal * terminal)2283 terminal_new_instance(struct terminal *terminal)
2284 {
2285 	struct terminal *new_terminal;
2286 
2287 	new_terminal = terminal_create(terminal->display);
2288 	if (terminal_run(new_terminal, option_shell))
2289 		terminal_destroy(new_terminal);
2290 }
2291 
2292 static int
handle_bound_key(struct terminal * terminal,struct input * input,uint32_t sym,uint32_t time)2293 handle_bound_key(struct terminal *terminal,
2294 		 struct input *input, uint32_t sym, uint32_t time)
2295 {
2296 	switch (sym) {
2297 	case XKB_KEY_X:
2298 		/* Cut selection; terminal doesn't do cut, fall
2299 		 * through to copy. */
2300 	case XKB_KEY_C:
2301 		terminal_copy(terminal, input);
2302 		return 1;
2303 	case XKB_KEY_V:
2304 		terminal_paste(terminal, input);
2305 		return 1;
2306 	case XKB_KEY_N:
2307 		terminal_new_instance(terminal);
2308 		return 1;
2309 
2310 	case XKB_KEY_Up:
2311 		if (!terminal->scrolling)
2312 			terminal->saved_start = terminal->start;
2313 		if (terminal->start == terminal->end - terminal->log_size)
2314 			return 1;
2315 
2316 		terminal->scrolling = 1;
2317 		terminal->start--;
2318 		terminal->row++;
2319 		terminal->selection_start_row++;
2320 		terminal->selection_end_row++;
2321 		widget_schedule_redraw(terminal->widget);
2322 		return 1;
2323 
2324 	case XKB_KEY_Down:
2325 		if (!terminal->scrolling)
2326 			terminal->saved_start = terminal->start;
2327 
2328 		if (terminal->start == terminal->saved_start)
2329 			return 1;
2330 
2331 		terminal->scrolling = 1;
2332 		terminal->start++;
2333 		terminal->row--;
2334 		terminal->selection_start_row--;
2335 		terminal->selection_end_row--;
2336 		widget_schedule_redraw(terminal->widget);
2337 		return 1;
2338 
2339 	default:
2340 		return 0;
2341 	}
2342 }
2343 
2344 static void
key_handler(struct window * window,struct input * input,uint32_t time,uint32_t key,uint32_t sym,enum wl_keyboard_key_state state,void * data)2345 key_handler(struct window *window, struct input *input, uint32_t time,
2346 	    uint32_t key, uint32_t sym, enum wl_keyboard_key_state state,
2347 	    void *data)
2348 {
2349 	struct terminal *terminal = data;
2350 	char ch[MAX_RESPONSE];
2351 	uint32_t modifiers, serial;
2352 	int ret, len = 0, d;
2353 	bool convert_utf8 = true;
2354 
2355 	modifiers = input_get_modifiers(input);
2356 	if ((modifiers & MOD_CONTROL_MASK) &&
2357 	    (modifiers & MOD_SHIFT_MASK) &&
2358 	    state == WL_KEYBOARD_KEY_STATE_PRESSED &&
2359 	    handle_bound_key(terminal, input, sym, time))
2360 		return;
2361 
2362 	/* Map keypad symbols to 'normal' equivalents before processing */
2363 	switch (sym) {
2364 	case XKB_KEY_KP_Space:
2365 		sym = XKB_KEY_space;
2366 		break;
2367 	case XKB_KEY_KP_Tab:
2368 		sym = XKB_KEY_Tab;
2369 		break;
2370 	case XKB_KEY_KP_Enter:
2371 		sym = XKB_KEY_Return;
2372 		break;
2373 	case XKB_KEY_KP_Left:
2374 		sym = XKB_KEY_Left;
2375 		break;
2376 	case XKB_KEY_KP_Up:
2377 		sym = XKB_KEY_Up;
2378 		break;
2379 	case XKB_KEY_KP_Right:
2380 		sym = XKB_KEY_Right;
2381 		break;
2382 	case XKB_KEY_KP_Down:
2383 		sym = XKB_KEY_Down;
2384 		break;
2385 	case XKB_KEY_KP_Equal:
2386 		sym = XKB_KEY_equal;
2387 		break;
2388 	case XKB_KEY_KP_Multiply:
2389 		sym = XKB_KEY_asterisk;
2390 		break;
2391 	case XKB_KEY_KP_Add:
2392 		sym = XKB_KEY_plus;
2393 		break;
2394 	case XKB_KEY_KP_Separator:
2395 		/* Note this is actually locale-dependent and should mostly be
2396 		 * a comma.  But leave it as period until we one day start
2397 		 * doing the right thing. */
2398 		sym = XKB_KEY_period;
2399 		break;
2400 	case XKB_KEY_KP_Subtract:
2401 		sym = XKB_KEY_minus;
2402 		break;
2403 	case XKB_KEY_KP_Decimal:
2404 		sym = XKB_KEY_period;
2405 		break;
2406 	case XKB_KEY_KP_Divide:
2407 		sym = XKB_KEY_slash;
2408 		break;
2409 	case XKB_KEY_KP_0:
2410 	case XKB_KEY_KP_1:
2411 	case XKB_KEY_KP_2:
2412 	case XKB_KEY_KP_3:
2413 	case XKB_KEY_KP_4:
2414 	case XKB_KEY_KP_5:
2415 	case XKB_KEY_KP_6:
2416 	case XKB_KEY_KP_7:
2417 	case XKB_KEY_KP_8:
2418 	case XKB_KEY_KP_9:
2419 		sym = (sym - XKB_KEY_KP_0) + XKB_KEY_0;
2420 		break;
2421 	default:
2422 		break;
2423 	}
2424 
2425 	switch (sym) {
2426 	case XKB_KEY_BackSpace:
2427 		if (modifiers & MOD_ALT_MASK)
2428 			ch[len++] = 0x1b;
2429 		ch[len++] = 0x7f;
2430 		break;
2431 	case XKB_KEY_Tab:
2432 	case XKB_KEY_Linefeed:
2433 	case XKB_KEY_Clear:
2434 	case XKB_KEY_Pause:
2435 	case XKB_KEY_Scroll_Lock:
2436 	case XKB_KEY_Sys_Req:
2437 	case XKB_KEY_Escape:
2438 		ch[len++] = sym & 0x7f;
2439 		break;
2440 
2441 	case XKB_KEY_Return:
2442 		if (terminal->mode & MODE_LF_NEWLINE) {
2443 			ch[len++] = 0x0D;
2444 			ch[len++] = 0x0A;
2445 		} else {
2446 			ch[len++] = 0x0D;
2447 		}
2448 		break;
2449 
2450 	case XKB_KEY_Shift_L:
2451 	case XKB_KEY_Shift_R:
2452 	case XKB_KEY_Control_L:
2453 	case XKB_KEY_Control_R:
2454 	case XKB_KEY_Alt_L:
2455 	case XKB_KEY_Alt_R:
2456 	case XKB_KEY_Meta_L:
2457 	case XKB_KEY_Meta_R:
2458 	case XKB_KEY_Super_L:
2459 	case XKB_KEY_Super_R:
2460 	case XKB_KEY_Hyper_L:
2461 	case XKB_KEY_Hyper_R:
2462 		break;
2463 
2464 	case XKB_KEY_Insert:
2465 		len = function_key_response('[', 2, modifiers, '~', ch);
2466 		break;
2467 	case XKB_KEY_Delete:
2468 		if (terminal->mode & MODE_DELETE_SENDS_DEL) {
2469 			ch[len++] = '\x04';
2470 		} else {
2471 			len = function_key_response('[', 3, modifiers, '~', ch);
2472 		}
2473 		break;
2474 	case XKB_KEY_Page_Up:
2475 		len = function_key_response('[', 5, modifiers, '~', ch);
2476 		break;
2477 	case XKB_KEY_Page_Down:
2478 		len = function_key_response('[', 6, modifiers, '~', ch);
2479 		break;
2480 	case XKB_KEY_F1:
2481 		len = function_key_response('O', 1, modifiers, 'P', ch);
2482 		break;
2483 	case XKB_KEY_F2:
2484 		len = function_key_response('O', 1, modifiers, 'Q', ch);
2485 		break;
2486 	case XKB_KEY_F3:
2487 		len = function_key_response('O', 1, modifiers, 'R', ch);
2488 		break;
2489 	case XKB_KEY_F4:
2490 		len = function_key_response('O', 1, modifiers, 'S', ch);
2491 		break;
2492 	case XKB_KEY_F5:
2493 		len = function_key_response('[', 15, modifiers, '~', ch);
2494 		break;
2495 	case XKB_KEY_F6:
2496 		len = function_key_response('[', 17, modifiers, '~', ch);
2497 		break;
2498 	case XKB_KEY_F7:
2499 		len = function_key_response('[', 18, modifiers, '~', ch);
2500 		break;
2501 	case XKB_KEY_F8:
2502 		len = function_key_response('[', 19, modifiers, '~', ch);
2503 		break;
2504 	case XKB_KEY_F9:
2505 		len = function_key_response('[', 20, modifiers, '~', ch);
2506 		break;
2507 	case XKB_KEY_F10:
2508 		len = function_key_response('[', 21, modifiers, '~', ch);
2509 		break;
2510 	case XKB_KEY_F12:
2511 		len = function_key_response('[', 24, modifiers, '~', ch);
2512 		break;
2513 	default:
2514 		/* Handle special keys with alternate mappings */
2515 		len = apply_key_map(terminal->key_mode, sym, modifiers, ch);
2516 		if (len != 0) break;
2517 
2518 		if (modifiers & MOD_CONTROL_MASK) {
2519 			if (sym >= '3' && sym <= '7')
2520 				sym = (sym & 0x1f) + 8;
2521 
2522 			if (!((sym >= '!' && sym <= '/') ||
2523 				(sym >= '8' && sym <= '?') ||
2524 				(sym >= '0' && sym <= '2'))) sym = sym & 0x1f;
2525 			else if (sym == '2') sym = 0x00;
2526 			else if (sym == '/') sym = 0x1F;
2527 			else if (sym == '8' || sym == '?') sym = 0x7F;
2528 		}
2529 		if (modifiers & MOD_ALT_MASK) {
2530 			if (terminal->mode & MODE_ALT_SENDS_ESC) {
2531 				ch[len++] = 0x1b;
2532 			} else {
2533 				sym = sym | 0x80;
2534 				convert_utf8 = false;
2535 			}
2536 		}
2537 
2538 		if ((sym < 128) ||
2539 		    (!convert_utf8 && sym < 256)) {
2540 			ch[len++] = sym;
2541 		} else {
2542 			ret = xkb_keysym_to_utf8(sym, ch + len,
2543 						 MAX_RESPONSE - len);
2544 			if (ret < 0)
2545 				fprintf(stderr,
2546 					"Warning: buffer too small to encode "
2547 					"UTF8 character\n");
2548 			else
2549 				len += ret;
2550 		}
2551 
2552 		break;
2553 	}
2554 
2555 	if (state == WL_KEYBOARD_KEY_STATE_PRESSED && len > 0) {
2556 		if (terminal->scrolling) {
2557 			d = terminal->saved_start - terminal->start;
2558 			terminal->row -= d;
2559 			terminal->selection_start_row -= d;
2560 			terminal->selection_end_row -= d;
2561 			terminal->start = terminal->saved_start;
2562 			terminal->scrolling = 0;
2563 			widget_schedule_redraw(terminal->widget);
2564 		}
2565 
2566 		terminal_write(terminal, ch, len);
2567 
2568 		/* Hide cursor, except if this was coming from a
2569 		 * repeating key press. */
2570 		serial = display_get_serial(terminal->display);
2571 		if (terminal->hide_cursor_serial != serial) {
2572 			input_set_pointer_image(input, CURSOR_BLANK);
2573 			terminal->hide_cursor_serial = serial;
2574 		}
2575 	}
2576 }
2577 
2578 static void
keyboard_focus_handler(struct window * window,struct input * device,void * data)2579 keyboard_focus_handler(struct window *window,
2580 		       struct input *device, void *data)
2581 {
2582 	struct terminal *terminal = data;
2583 
2584 	window_schedule_redraw(terminal->window);
2585 }
2586 
wordsep(int ch)2587 static int wordsep(int ch)
2588 {
2589 	const char extra[] = "-,./?%&#:_=+@~";
2590 
2591 	if (ch > 127 || ch < 0)
2592 		return 1;
2593 
2594 	return ch == 0 || !(isalpha(ch) || isdigit(ch) || strchr(extra, ch));
2595 }
2596 
2597 static int
recompute_selection(struct terminal * terminal)2598 recompute_selection(struct terminal *terminal)
2599 {
2600 	struct rectangle allocation;
2601 	int col, x, width, height;
2602 	int start_row, end_row;
2603 	int word_start, eol;
2604 	int side_margin, top_margin;
2605 	int start_x, end_x;
2606 	int cw, ch;
2607 	union utf8_char *data;
2608 
2609 	cw = terminal->average_width;
2610 	ch = terminal->extents.height;
2611 	widget_get_allocation(terminal->widget, &allocation);
2612 	width = terminal->width * cw;
2613 	height = terminal->height * ch;
2614 	side_margin = allocation.x + (allocation.width - width) / 2;
2615 	top_margin = allocation.y + (allocation.height - height) / 2;
2616 
2617 	start_row = (terminal->selection_start_y - top_margin + ch) / ch - 1;
2618 	end_row = (terminal->selection_end_y - top_margin + ch) / ch - 1;
2619 
2620 	if (start_row < end_row ||
2621 	    (start_row == end_row &&
2622 	     terminal->selection_start_x < terminal->selection_end_x)) {
2623 		terminal->selection_start_row = start_row;
2624 		terminal->selection_end_row = end_row;
2625 		start_x = terminal->selection_start_x;
2626 		end_x = terminal->selection_end_x;
2627 	} else {
2628 		terminal->selection_start_row = end_row;
2629 		terminal->selection_end_row = start_row;
2630 		start_x = terminal->selection_end_x;
2631 		end_x = terminal->selection_start_x;
2632 	}
2633 
2634 	eol = 0;
2635 	if (terminal->selection_start_row < 0) {
2636 		terminal->selection_start_row = 0;
2637 		terminal->selection_start_col = 0;
2638 	} else {
2639 		x = side_margin + cw / 2;
2640 		data = terminal_get_row(terminal,
2641 					terminal->selection_start_row);
2642 		word_start = 0;
2643 		for (col = 0; col < terminal->width; col++, x += cw) {
2644 			if (col == 0 || wordsep(data[col - 1].ch))
2645 				word_start = col;
2646 			if (data[col].ch != 0)
2647 				eol = col + 1;
2648 			if (start_x < x)
2649 				break;
2650 		}
2651 
2652 		switch (terminal->dragging) {
2653 		case SELECT_LINE:
2654 			terminal->selection_start_col = 0;
2655 			break;
2656 		case SELECT_WORD:
2657 			terminal->selection_start_col = word_start;
2658 			break;
2659 		case SELECT_CHAR:
2660 			terminal->selection_start_col = col;
2661 			break;
2662 		}
2663 	}
2664 
2665 	if (terminal->selection_end_row >= terminal->height) {
2666 		terminal->selection_end_row = terminal->height;
2667 		terminal->selection_end_col = 0;
2668 	} else {
2669 		x = side_margin + cw / 2;
2670 		data = terminal_get_row(terminal, terminal->selection_end_row);
2671 		for (col = 0; col < terminal->width; col++, x += cw) {
2672 			if (terminal->dragging == SELECT_CHAR && end_x < x)
2673 				break;
2674 			if (terminal->dragging == SELECT_WORD &&
2675 			    end_x < x && wordsep(data[col].ch))
2676 				break;
2677 		}
2678 		terminal->selection_end_col = col;
2679 	}
2680 
2681 	if (terminal->selection_end_col != terminal->selection_start_col ||
2682 	    terminal->selection_start_row != terminal->selection_end_row) {
2683 		col = terminal->selection_end_col;
2684 		if (col > 0 && data[col - 1].ch == 0)
2685 			terminal->selection_end_col = terminal->width;
2686 		data = terminal_get_row(terminal, terminal->selection_start_row);
2687 		if (data[terminal->selection_start_col].ch == 0)
2688 			terminal->selection_start_col = eol;
2689 	}
2690 
2691 	return 1;
2692 }
2693 
2694 static void
terminal_minimize(struct terminal * terminal)2695 terminal_minimize(struct terminal *terminal)
2696 {
2697 	window_set_minimized(terminal->window);
2698 }
2699 
2700 static void
menu_func(void * data,struct input * input,int index)2701 menu_func(void *data, struct input *input, int index)
2702 {
2703 	struct window *window = data;
2704 	struct terminal *terminal = window_get_user_data(window);
2705 
2706 	fprintf(stderr, "picked entry %d\n", index);
2707 
2708 	switch (index) {
2709 	case 0:
2710 		terminal_new_instance(terminal);
2711 		break;
2712 	case 1:
2713 		terminal_copy(terminal, input);
2714 		break;
2715 	case 2:
2716 		terminal_paste(terminal, input);
2717 		break;
2718 	case 3:
2719 		terminal_minimize(terminal);
2720 		break;
2721 	}
2722 }
2723 
2724 static void
show_menu(struct terminal * terminal,struct input * input,uint32_t time)2725 show_menu(struct terminal *terminal, struct input *input, uint32_t time)
2726 {
2727 	int32_t x, y;
2728 	static const char *entries[] = {
2729 		"Open Terminal", "Copy", "Paste", "Minimize"
2730 	};
2731 
2732 	input_get_position(input, &x, &y);
2733 	window_show_menu(terminal->display, input, time, terminal->window,
2734 			 x - 10, y - 10, menu_func,
2735 			 entries, ARRAY_LENGTH(entries));
2736 }
2737 
2738 static void
click_handler(struct widget * widget,struct terminal * terminal,struct input * input,int32_t x,int32_t y,uint32_t time)2739 click_handler(struct widget *widget, struct terminal *terminal,
2740 		struct input *input, int32_t x, int32_t y,
2741 		uint32_t time)
2742 {
2743 	if (time - terminal->click_time < 500)
2744 		terminal->click_count++;
2745 	else
2746 		terminal->click_count = 1;
2747 
2748 	terminal->click_time = time;
2749 	terminal->dragging = (terminal->click_count - 1) % 3 + SELECT_CHAR;
2750 
2751 	terminal->selection_end_x = terminal->selection_start_x = x;
2752 	terminal->selection_end_y = terminal->selection_start_y = y;
2753 	if (recompute_selection(terminal))
2754 			widget_schedule_redraw(widget);
2755 }
2756 
2757 static void
button_handler(struct widget * widget,struct input * input,uint32_t time,uint32_t button,enum wl_pointer_button_state state,void * data)2758 button_handler(struct widget *widget,
2759 	       struct input *input, uint32_t time,
2760 	       uint32_t button,
2761 	       enum wl_pointer_button_state state, void *data)
2762 {
2763 	struct terminal *terminal = data;
2764 	int32_t x, y;
2765 
2766 	switch (button) {
2767 	case BTN_LEFT:
2768 		if (state == WL_POINTER_BUTTON_STATE_PRESSED) {
2769 			input_get_position(input, &x, &y);
2770 			click_handler(widget, terminal, input, x, y, time);
2771 		} else {
2772 			terminal->dragging = SELECT_NONE;
2773 		}
2774 		break;
2775 
2776 	case BTN_RIGHT:
2777 		if (state == WL_POINTER_BUTTON_STATE_PRESSED)
2778 			show_menu(terminal, input, time);
2779 		break;
2780 	}
2781 }
2782 
2783 static int
enter_handler(struct widget * widget,struct input * input,float x,float y,void * data)2784 enter_handler(struct widget *widget,
2785 	      struct input *input, float x, float y, void *data)
2786 {
2787 	return CURSOR_IBEAM;
2788 }
2789 
2790 static int
motion_handler(struct widget * widget,struct input * input,uint32_t time,float x,float y,void * data)2791 motion_handler(struct widget *widget,
2792 	       struct input *input, uint32_t time,
2793 	       float x, float y, void *data)
2794 {
2795 	struct terminal *terminal = data;
2796 
2797 	if (terminal->dragging) {
2798 		input_get_position(input,
2799 				   &terminal->selection_end_x,
2800 				   &terminal->selection_end_y);
2801 
2802 		if (recompute_selection(terminal))
2803 			widget_schedule_redraw(widget);
2804 	}
2805 
2806 	return CURSOR_IBEAM;
2807 }
2808 
2809 /* This magnitude is chosen rather arbitrarily. Really, the scrolling
2810  * should happen on a (fractional) pixel basis, not a line basis. */
2811 #define AXIS_UNITS_PER_LINE 256
2812 
2813 static void
axis_handler(struct widget * widget,struct input * input,uint32_t time,uint32_t axis,wl_fixed_t value,void * data)2814 axis_handler(struct widget *widget,
2815 	     struct input *input, uint32_t time,
2816 	     uint32_t axis,
2817 	     wl_fixed_t value,
2818 	     void *data)
2819 {
2820 	struct terminal *terminal = data;
2821 	int lines;
2822 
2823 	if (axis != WL_POINTER_AXIS_VERTICAL_SCROLL)
2824 		return;
2825 
2826 	terminal->smooth_scroll += value;
2827 	lines = terminal->smooth_scroll / AXIS_UNITS_PER_LINE;
2828 	terminal->smooth_scroll -= lines * AXIS_UNITS_PER_LINE;
2829 
2830 	if (lines > 0) {
2831 		if (terminal->scrolling) {
2832 			if ((uint32_t)lines > terminal->saved_start - terminal->start)
2833 				lines = terminal->saved_start - terminal->start;
2834 		} else {
2835 			lines = 0;
2836 		}
2837 	} else if (lines < 0) {
2838 		uint32_t neg_lines = -lines;
2839 
2840 		if (neg_lines > terminal->log_size + terminal->start - terminal->end)
2841 			lines = terminal->end - terminal->log_size - terminal->start;
2842 	}
2843 
2844 	if (lines) {
2845 		if (!terminal->scrolling)
2846 			terminal->saved_start = terminal->start;
2847 		terminal->scrolling = 1;
2848 
2849 		terminal->start += lines;
2850 		terminal->row -= lines;
2851 		terminal->selection_start_row -= lines;
2852 		terminal->selection_end_row -= lines;
2853 
2854 		widget_schedule_redraw(widget);
2855 	}
2856 }
2857 
2858 static void
output_handler(struct window * window,struct output * output,int enter,void * data)2859 output_handler(struct window *window, struct output *output, int enter,
2860 	       void *data)
2861 {
2862 	if (enter)
2863 		window_set_buffer_transform(window, output_get_transform(output));
2864 	window_set_buffer_scale(window, window_get_output_scale(window));
2865 	window_schedule_redraw(window);
2866 }
2867 
2868 static void
touch_down_handler(struct widget * widget,struct input * input,uint32_t serial,uint32_t time,int32_t id,float x,float y,void * data)2869 touch_down_handler(struct widget *widget, struct input *input,
2870 		uint32_t serial, uint32_t time, int32_t id,
2871 		float x, float y, void *data)
2872 {
2873 	struct terminal *terminal = data;
2874 
2875 	if (id == 0)
2876 		click_handler(widget, terminal, input, x, y, time);
2877 }
2878 
2879 static void
touch_up_handler(struct widget * widget,struct input * input,uint32_t serial,uint32_t time,int32_t id,void * data)2880 touch_up_handler(struct widget *widget, struct input *input,
2881 		uint32_t serial, uint32_t time, int32_t id, void *data)
2882 {
2883 	struct terminal *terminal = data;
2884 
2885 	if (id == 0)
2886 		terminal->dragging = SELECT_NONE;
2887 }
2888 
2889 static void
touch_motion_handler(struct widget * widget,struct input * input,uint32_t time,int32_t id,float x,float y,void * data)2890 touch_motion_handler(struct widget *widget, struct input *input,
2891 		uint32_t time, int32_t id, float x, float y, void *data)
2892 {
2893 	struct terminal *terminal = data;
2894 
2895 	if (terminal->dragging &&
2896 		id == 0) {
2897 		terminal->selection_end_x = (int)x;
2898 		terminal->selection_end_y = (int)y;
2899 
2900 		if (recompute_selection(terminal))
2901 			widget_schedule_redraw(widget);
2902 	}
2903 }
2904 
2905 #ifndef howmany
2906 #define howmany(x, y) (((x) + ((y) - 1)) / (y))
2907 #endif
2908 
2909 static struct terminal *
terminal_create(struct display * display)2910 terminal_create(struct display *display)
2911 {
2912 	struct terminal *terminal;
2913 	cairo_surface_t *surface;
2914 	cairo_t *cr;
2915 	cairo_text_extents_t text_extents;
2916 
2917 	terminal = xzalloc(sizeof *terminal);
2918 	terminal->color_scheme = &DEFAULT_COLORS;
2919 	terminal_init(terminal);
2920 	terminal->margin_top = 0;
2921 	terminal->margin_bottom = -1;
2922 	terminal->window = window_create(display);
2923 	terminal->widget = window_frame_create(terminal->window, terminal);
2924 	terminal->title = xstrdup("Wayland Terminal");
2925 	window_set_title(terminal->window, terminal->title);
2926 	widget_set_transparent(terminal->widget, 0);
2927 
2928 	init_state_machine(&terminal->state_machine);
2929 	init_color_table(terminal);
2930 
2931 	terminal->display = display;
2932 	terminal->margin = 5;
2933 	terminal->buffer_height = 1024;
2934 	terminal->end = 1;
2935 
2936 	window_set_user_data(terminal->window, terminal);
2937 	window_set_key_handler(terminal->window, key_handler);
2938 	window_set_keyboard_focus_handler(terminal->window,
2939 					  keyboard_focus_handler);
2940 	window_set_fullscreen_handler(terminal->window, fullscreen_handler);
2941 	window_set_output_handler(terminal->window, output_handler);
2942 	window_set_close_handler(terminal->window, close_handler);
2943 	window_set_state_changed_handler(terminal->window, state_changed_handler);
2944 
2945 	window_set_data_handler(terminal->window, data_handler);
2946 	window_set_drop_handler(terminal->window, drop_handler);
2947 
2948 	widget_set_redraw_handler(terminal->widget, redraw_handler);
2949 	widget_set_resize_handler(terminal->widget, resize_handler);
2950 	widget_set_button_handler(terminal->widget, button_handler);
2951 	widget_set_enter_handler(terminal->widget, enter_handler);
2952 	widget_set_motion_handler(terminal->widget, motion_handler);
2953 	widget_set_axis_handler(terminal->widget, axis_handler);
2954 	widget_set_touch_up_handler(terminal->widget, touch_up_handler);
2955 	widget_set_touch_down_handler(terminal->widget, touch_down_handler);
2956 	widget_set_touch_motion_handler(terminal->widget, touch_motion_handler);
2957 
2958 	surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
2959 	cr = cairo_create(surface);
2960 	cairo_set_font_size(cr, option_font_size);
2961 	cairo_select_font_face (cr, option_font,
2962 				CAIRO_FONT_SLANT_NORMAL,
2963 				CAIRO_FONT_WEIGHT_BOLD);
2964 	terminal->font_bold = cairo_get_scaled_font (cr);
2965 	cairo_scaled_font_reference(terminal->font_bold);
2966 
2967 	cairo_select_font_face (cr, option_font,
2968 				CAIRO_FONT_SLANT_NORMAL,
2969 				CAIRO_FONT_WEIGHT_NORMAL);
2970 	terminal->font_normal = cairo_get_scaled_font (cr);
2971 	cairo_scaled_font_reference(terminal->font_normal);
2972 
2973 	cairo_font_extents(cr, &terminal->extents);
2974 
2975 	/* Compute the average ascii glyph width */
2976 	cairo_text_extents(cr, TERMINAL_DRAW_SINGLE_WIDE_CHARACTERS,
2977 			   &text_extents);
2978 	terminal->average_width = howmany
2979 		(text_extents.width,
2980 		 strlen(TERMINAL_DRAW_SINGLE_WIDE_CHARACTERS));
2981 	terminal->average_width = ceil(terminal->average_width);
2982 
2983 	cairo_destroy(cr);
2984 	cairo_surface_destroy(surface);
2985 
2986 	terminal_resize(terminal, 20, 5); /* Set minimum size first */
2987 	terminal_resize(terminal, 80, 25);
2988 
2989 	wl_list_insert(terminal_list.prev, &terminal->link);
2990 
2991 	return terminal;
2992 }
2993 
2994 static void
terminal_destroy(struct terminal * terminal)2995 terminal_destroy(struct terminal *terminal)
2996 {
2997 	event_free(terminal->masterev);
2998 	window_destroy(terminal->window);
2999 	close(terminal->master);
3000 	wl_list_remove(&terminal->link);
3001 
3002 	if (wl_list_empty(&terminal_list))
3003 		display_exit(terminal->display);
3004 
3005 	free(terminal->title);
3006 	free(terminal);
3007 }
3008 
3009 static void
io_handler(evutil_socket_t fd,short what,void * arg)3010 io_handler(evutil_socket_t fd, short what, void *arg)
3011 {
3012 	struct task *task = (struct task *)arg;
3013 	struct terminal *terminal =
3014 		container_of(task, struct terminal, io_task);
3015 	char buffer[256];
3016 	int len;
3017 
3018 	len = read(terminal->master, buffer, sizeof buffer);
3019 	if (len <= 0)
3020 		terminal_destroy(terminal);
3021 	else
3022 		terminal_data(terminal, buffer, len);
3023 }
3024 
3025 static int
terminal_run(struct terminal * terminal,const char * path)3026 terminal_run(struct terminal *terminal, const char *path)
3027 {
3028 	int master;
3029 	pid_t pid;
3030 
3031 	pid = forkpty(&master, NULL, NULL, NULL);
3032 	if (pid == 0) {
3033 		setenv("TERM", option_term, 1);
3034 		setenv("COLORTERM", option_term, 1);
3035 		if (execl(path, path, NULL)) {
3036 			printf("exec failed: %s\n", strerror(errno));
3037 			exit(EXIT_FAILURE);
3038 		}
3039 	} else if (pid < 0) {
3040 		fprintf(stderr, "failed to fork and create pty (%s).\n",
3041 		    strerror(errno));
3042 		return -1;
3043 	}
3044 
3045 	terminal->master = master;
3046 	fcntl(master, F_SETFL, O_NONBLOCK);
3047 	terminal->io_task.run = io_handler;
3048 	terminal->masterev = display_watch_fd(terminal->display,
3049 	    terminal->master, EV_PERSIST | EV_READ, &terminal->io_task);
3050 
3051 	if (option_fullscreen)
3052 		window_set_fullscreen(terminal->window, 1);
3053 	else
3054 		terminal_resize(terminal, 80, 24);
3055 
3056 	return 0;
3057 }
3058 
3059 static const struct weston_option terminal_options[] = {
3060 	{ WESTON_OPTION_BOOLEAN, "fullscreen", 'f', &option_fullscreen },
3061 	{ WESTON_OPTION_STRING, "font", 0, &option_font },
3062 	{ WESTON_OPTION_INTEGER, "font-size", 0, &option_font_size },
3063 	{ WESTON_OPTION_STRING, "shell", 0, &option_shell },
3064 };
3065 
main(int argc,char * argv[])3066 int main(int argc, char *argv[])
3067 {
3068 	struct display *d;
3069 	struct terminal *terminal;
3070 	const char *config_file;
3071 	struct weston_config *config;
3072 	struct weston_config_section *s;
3073 
3074 	/* as wcwidth is locale-dependent,
3075 	   wcwidth needs setlocale call to function properly. */
3076 	setlocale(LC_ALL, "");
3077 
3078 	option_shell = getenv("SHELL");
3079 	if (!option_shell)
3080 		option_shell = "/bin/bash";
3081 
3082 	config_file = weston_config_get_name_from_env();
3083 	config = weston_config_parse(config_file);
3084 	s = weston_config_get_section(config, "terminal", NULL, NULL);
3085 	weston_config_section_get_string(s, "font", &option_font, "mono");
3086 	weston_config_section_get_int(s, "font-size", &option_font_size, 14);
3087 	weston_config_section_get_string(s, "term", &option_term, "xterm");
3088 	weston_config_destroy(config);
3089 
3090 	if (parse_options(terminal_options,
3091 			  ARRAY_LENGTH(terminal_options), &argc, argv) > 1) {
3092 		printf("Usage: %s [OPTIONS]\n"
3093 		       "  --fullscreen or -f\n"
3094 		       "  --font=NAME\n"
3095 		       "  --font-size=SIZE\n"
3096 		       "  --shell=NAME\n", argv[0]);
3097 		return 1;
3098 	}
3099 
3100 	d = display_create(&argc, argv);
3101 	if (d == NULL) {
3102 		fprintf(stderr, "failed to create display: %s\n",
3103 		    strerror(errno));
3104 		return -1;
3105 	}
3106 
3107 	wl_list_init(&terminal_list);
3108 	terminal = terminal_create(d);
3109 	if (terminal_run(terminal, option_shell))
3110 		exit(EXIT_FAILURE);
3111 
3112 	display_run(d);
3113 
3114 	return 0;
3115 }
3116