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