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