Add minimum size for terminal
[profile/ivi/weston.git] / clients / terminal.c
1 /*
2  * Copyright © 2008 Kristian Høgsberg
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that copyright
7  * notice and this permission notice appear in supporting documentation, and
8  * that the name of the copyright holders not be used in advertising or
9  * publicity pertaining to distribution of the software without specific,
10  * written prior permission.  The copyright holders make no representations
11  * about the suitability of this software for any purpose.  It is provided "as
12  * is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
20  * OF THIS SOFTWARE.
21  */
22
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <math.h>
30 #include <time.h>
31 #include <pty.h>
32 #include <ctype.h>
33 #include <cairo.h>
34 #include <sys/epoll.h>
35
36 #include <wayland-client.h>
37
38 #include "window.h"
39
40 static int option_fullscreen;
41
42 #define MOD_SHIFT       0x01
43 #define MOD_ALT         0x02
44 #define MOD_CTRL        0x04
45
46 #define ATTRMASK_BOLD           0x01
47 #define ATTRMASK_UNDERLINE      0x02
48 #define ATTRMASK_BLINK          0x04
49 #define ATTRMASK_INVERSE        0x08
50 #define ATTRMASK_CONCEALED      0x10
51
52 /* Buffer sizes */
53 #define MAX_RESPONSE            256
54 #define MAX_ESCAPE              255
55
56 /* Terminal modes */
57 #define MODE_SHOW_CURSOR        0x00000001
58 #define MODE_INVERSE            0x00000002
59 #define MODE_AUTOWRAP           0x00000004
60 #define MODE_AUTOREPEAT         0x00000008
61 #define MODE_LF_NEWLINE         0x00000010
62 #define MODE_IRM                0x00000020
63 #define MODE_DELETE_SENDS_DEL   0x00000040
64 #define MODE_ALT_SENDS_ESC      0x00000080
65
66 union utf8_char {
67         unsigned char byte[4];
68         uint32_t ch;
69 };
70
71 enum utf8_state {
72         utf8state_start,
73         utf8state_accept,
74         utf8state_reject,
75         utf8state_expect3,
76         utf8state_expect2,
77         utf8state_expect1
78 };
79
80 struct utf8_state_machine {
81         enum utf8_state state;
82         int len;
83         union utf8_char s;
84 };
85
86 static void
87 init_state_machine(struct utf8_state_machine *machine)
88 {
89         machine->state = utf8state_start;
90         machine->len = 0;
91         machine->s.ch = 0;
92 }
93
94 static enum utf8_state
95 utf8_next_char(struct utf8_state_machine *machine, unsigned char c)
96 {
97         switch(machine->state) {
98         case utf8state_start:
99         case utf8state_accept:
100         case utf8state_reject:
101                 machine->s.ch = 0;
102                 machine->len = 0;
103                 if(c == 0xC0 || c == 0xC1) {
104                         /* overlong encoding, reject */
105                         machine->state = utf8state_reject;
106                 } else if((c & 0x80) == 0) {
107                         /* single byte, accept */
108                         machine->s.byte[machine->len++] = c;
109                         machine->state = utf8state_accept;
110                 } else if((c & 0xC0) == 0x80) {
111                         /* parser out of sync, ignore byte */
112                         machine->state = utf8state_start;
113                 } else if((c & 0xE0) == 0xC0) {
114                         /* start of two byte sequence */
115                         machine->s.byte[machine->len++] = c;
116                         machine->state = utf8state_expect1;
117                 } else if((c & 0xF0) == 0xE0) {
118                         /* start of three byte sequence */
119                         machine->s.byte[machine->len++] = c;
120                         machine->state = utf8state_expect2;
121                 } else if((c & 0xF8) == 0xF0) {
122                         /* start of four byte sequence */
123                         machine->s.byte[machine->len++] = c;
124                         machine->state = utf8state_expect3;
125                 } else {
126                         /* overlong encoding, reject */
127                         machine->state = utf8state_reject;
128                 }
129                 break;
130         case utf8state_expect3:
131                 machine->s.byte[machine->len++] = c;
132                 if((c & 0xC0) == 0x80) {
133                         /* all good, continue */
134                         machine->state = utf8state_expect2;
135                 } else {
136                         /* missing extra byte, reject */
137                         machine->state = utf8state_reject;
138                 }
139                 break;
140         case utf8state_expect2:
141                 machine->s.byte[machine->len++] = c;
142                 if((c & 0xC0) == 0x80) {
143                         /* all good, continue */
144                         machine->state = utf8state_expect1;
145                 } else {
146                         /* missing extra byte, reject */
147                         machine->state = utf8state_reject;
148                 }
149                 break;
150         case utf8state_expect1:
151                 machine->s.byte[machine->len++] = c;
152                 if((c & 0xC0) == 0x80) {
153                         /* all good, accept */
154                         machine->state = utf8state_accept;
155                 } else {
156                         /* missing extra byte, reject */
157                         machine->state = utf8state_reject;
158                 }
159                 break;
160         default:
161                 machine->state = utf8state_reject;
162                 break;
163         }
164         
165         return machine->state;
166 }
167
168 struct char_sub {
169         union utf8_char match;
170         union utf8_char replace;
171 };
172 /* Set last char_sub match to NULL char */
173 typedef struct char_sub *character_set;
174
175 struct char_sub CS_US[] = {
176         {{{0, }}, {{0, }}}
177 };
178 static struct char_sub CS_UK[] = {
179         {{{'#', 0, }}, {{0xC2, 0xA3, 0, }}}, /* POUND: £ */
180         {{{0, }}, {{0, }}}
181 };
182 static struct char_sub CS_SPECIAL[] = {
183         {{{'`', 0, }}, {{0xE2, 0x99, 0xA6, 0}}}, /* diamond: ♦ */
184         {{{'a', 0, }}, {{0xE2, 0x96, 0x92, 0}}}, /* 50% cell: ▒ */
185         {{{'b', 0, }}, {{0xE2, 0x90, 0x89, 0}}}, /* HT: ␉ */
186         {{{'c', 0, }}, {{0xE2, 0x90, 0x8C, 0}}}, /* FF: ␌ */
187         {{{'d', 0, }}, {{0xE2, 0x90, 0x8D, 0}}}, /* CR: ␍ */
188         {{{'e', 0, }}, {{0xE2, 0x90, 0x8A, 0}}}, /* LF: ␊ */
189         {{{'f', 0, }}, {{0xC2, 0xB0, 0, }}}, /* Degree: ° */
190         {{{'g', 0, }}, {{0xC2, 0xB1, 0, }}}, /* Plus/Minus: ± */
191         {{{'h', 0, }}, {{0xE2, 0x90, 0xA4, 0}}}, /* NL: ␤ */
192         {{{'i', 0, }}, {{0xE2, 0x90, 0x8B, 0}}}, /* VT: ␋ */
193         {{{'j', 0, }}, {{0xE2, 0x94, 0x98, 0}}}, /* CN_RB: ┘ */
194         {{{'k', 0, }}, {{0xE2, 0x94, 0x90, 0}}}, /* CN_RT: ┐ */
195         {{{'l', 0, }}, {{0xE2, 0x94, 0x8C, 0}}}, /* CN_LT: ┌ */
196         {{{'m', 0, }}, {{0xE2, 0x94, 0x94, 0}}}, /* CN_LB: └ */
197         {{{'n', 0, }}, {{0xE2, 0x94, 0xBC, 0}}}, /* CROSS: ┼ */
198         {{{'o', 0, }}, {{0xE2, 0x8E, 0xBA, 0}}}, /* Horiz. Scan Line 1: ⎺ */
199         {{{'p', 0, }}, {{0xE2, 0x8E, 0xBB, 0}}}, /* Horiz. Scan Line 3: ⎻ */
200         {{{'q', 0, }}, {{0xE2, 0x94, 0x80, 0}}}, /* Horiz. Scan Line 5: ─ */
201         {{{'r', 0, }}, {{0xE2, 0x8E, 0xBC, 0}}}, /* Horiz. Scan Line 7: ⎼ */
202         {{{'s', 0, }}, {{0xE2, 0x8E, 0xBD, 0}}}, /* Horiz. Scan Line 9: ⎽ */
203         {{{'t', 0, }}, {{0xE2, 0x94, 0x9C, 0}}}, /* TR: ├ */
204         {{{'u', 0, }}, {{0xE2, 0x94, 0xA4, 0}}}, /* TL: ┤ */
205         {{{'v', 0, }}, {{0xE2, 0x94, 0xB4, 0}}}, /* TU: ┴ */
206         {{{'w', 0, }}, {{0xE2, 0x94, 0xAC, 0}}}, /* TD: ┬ */
207         {{{'x', 0, }}, {{0xE2, 0x94, 0x82, 0}}}, /* V: │ */
208         {{{'y', 0, }}, {{0xE2, 0x89, 0xA4, 0}}}, /* LE: ≤ */
209         {{{'z', 0, }}, {{0xE2, 0x89, 0xA5, 0}}}, /* GE: ≥ */
210         {{{'{', 0, }}, {{0xCF, 0x80, 0, }}}, /* PI: π */
211         {{{'|', 0, }}, {{0xE2, 0x89, 0xA0, 0}}}, /* NEQ: ≠ */
212         {{{'}', 0, }}, {{0xC2, 0xA3, 0, }}}, /* POUND: £ */
213         {{{'~', 0, }}, {{0xE2, 0x8B, 0x85, 0}}}, /* DOT: ⋅ */
214         {{{0, }}, {{0, }}}
215 };
216
217 static void
218 apply_char_set(character_set cs, union utf8_char *utf8)
219 {
220         int i = 0;
221         
222         while (cs[i].match.byte[0]) {
223                 if ((*utf8).ch == cs[i].match.ch) {
224                         *utf8 = cs[i].replace;
225                         break;
226                 }
227                 i++;
228         }
229 }
230
231 struct key_map {
232         int sym;
233         int num;
234         char escape;
235         char code;
236 };
237 /* Set last key_sub sym to NULL */
238 typedef struct key_map *keyboard_mode;
239
240 static struct key_map KM_NORMAL[] = {
241         { XKB_KEY_Left,  1, '[', 'D' },
242         { XKB_KEY_Right, 1, '[', 'C' },
243         { XKB_KEY_Up,    1, '[', 'A' },
244         { XKB_KEY_Down,  1, '[', 'B' },
245         { XKB_KEY_Home,  1, '[', 'H' },
246         { XKB_KEY_End,   1, '[', 'F' },
247         { 0, 0, 0, 0 }
248 };
249 static struct key_map KM_APPLICATION[] = {
250         { XKB_KEY_Left,          1, 'O', 'D' },
251         { XKB_KEY_Right,         1, 'O', 'C' },
252         { XKB_KEY_Up,            1, 'O', 'A' },
253         { XKB_KEY_Down,          1, 'O', 'B' },
254         { XKB_KEY_Home,          1, 'O', 'H' },
255         { XKB_KEY_End,           1, 'O', 'F' },
256         { XKB_KEY_KP_Enter,      1, 'O', 'M' },
257         { XKB_KEY_KP_Multiply,   1, 'O', 'j' },
258         { XKB_KEY_KP_Add,        1, 'O', 'k' },
259         { XKB_KEY_KP_Separator,  1, 'O', 'l' },
260         { XKB_KEY_KP_Subtract,   1, 'O', 'm' },
261         { XKB_KEY_KP_Divide,     1, 'O', 'o' },
262         { 0, 0, 0, 0 }
263 };
264
265 static int
266 function_key_response(char escape, int num, uint32_t modifiers,
267                       char code, char *response)
268 {
269         int mod_num = 0;
270         int len;
271
272         if (modifiers & MOD_SHIFT_MASK) mod_num   |= 1;
273         if (modifiers & MOD_ALT_MASK) mod_num    |= 2;
274         if (modifiers & MOD_CONTROL_MASK) mod_num |= 4;
275
276         if (mod_num != 0)
277                 len = snprintf(response, MAX_RESPONSE, "\e[%d;%d%c",
278                                num, mod_num + 1, code);
279         else if (code != '~')
280                 len = snprintf(response, MAX_RESPONSE, "\e%c%c",
281                                escape, code);
282         else
283                 len = snprintf(response, MAX_RESPONSE, "\e%c%d%c",
284                                escape, num, code);
285
286         if (len >= MAX_RESPONSE)        return MAX_RESPONSE - 1;
287         else                            return len;
288 }
289
290 /* returns the number of bytes written into response,
291  * which must have room for MAX_RESPONSE bytes */
292 static int
293 apply_key_map(keyboard_mode mode, int sym, uint32_t modifiers, char *response)
294 {
295         struct key_map map;
296         int len = 0;
297         int i = 0;
298         
299         while (mode[i].sym) {
300                 map = mode[i++];
301                 if (sym == map.sym) {
302                         len = function_key_response(map.escape, map.num,
303                                                     modifiers, map.code,
304                                                     response);
305                         break;
306                 }
307         }
308         
309         return len;
310 }
311
312 struct terminal_color { double r, g, b, a; };
313 struct attr {
314         unsigned char fg, bg;
315         char a;        /* attributes format:
316                         * 76543210
317                         *    cilub */
318         char s;        /* in selection */
319 };
320 struct color_scheme {
321         struct terminal_color palette[16];
322         char border;
323         struct attr default_attr;
324 };
325
326 static void
327 attr_init(struct attr *data_attr, struct attr attr, int n)
328 {
329         int i;
330         for (i = 0; i < n; i++) {
331                 data_attr[i] = attr;
332         }
333 }
334
335 enum escape_state {
336         escape_state_normal = 0,
337         escape_state_escape,
338         escape_state_dcs,
339         escape_state_csi,
340         escape_state_osc,
341         escape_state_inner_escape,
342         escape_state_ignore,
343         escape_state_special
344 };
345
346 #define ESC_FLAG_WHAT   0x01
347 #define ESC_FLAG_GT     0x02
348 #define ESC_FLAG_BANG   0x04
349 #define ESC_FLAG_CASH   0x08
350 #define ESC_FLAG_SQUOTE 0x10
351 #define ESC_FLAG_DQUOTE 0x20
352 #define ESC_FLAG_SPACE  0x40
353
354 struct terminal {
355         struct window *window;
356         struct widget *widget;
357         struct display *display;
358         union utf8_char *data;
359         struct task io_task;
360         char *tab_ruler;
361         struct attr *data_attr;
362         struct attr curr_attr;
363         uint32_t mode;
364         char origin_mode;
365         char saved_origin_mode;
366         struct attr saved_attr;
367         union utf8_char last_char;
368         int margin_top, margin_bottom;
369         character_set cs, g0, g1;
370         character_set saved_cs, saved_g0, saved_g1;
371         keyboard_mode key_mode;
372         int data_pitch, attr_pitch;  /* The width in bytes of a line */
373         int width, height, start, row, column;
374         int saved_row, saved_column;
375         int send_cursor_position;
376         int fd, master;
377         uint32_t modifiers;
378         char escape[MAX_ESCAPE+1];
379         int escape_length;
380         enum escape_state state;
381         enum escape_state outer_state;
382         int escape_flags;
383         struct utf8_state_machine state_machine;
384         int margin;
385         int fullscreen;
386         int focused;
387         struct color_scheme *color_scheme;
388         struct terminal_color color_table[256];
389         cairo_font_extents_t extents;
390         cairo_scaled_font_t *font_normal, *font_bold;
391
392         struct wl_data_source *selection;
393         int32_t dragging;
394         int selection_start_x, selection_start_y;
395         int selection_end_x, selection_end_y;
396 };
397
398 /* Create default tab stops, every 8 characters */
399 static void
400 terminal_init_tabs(struct terminal *terminal)
401 {
402         int i = 0;
403         
404         while (i < terminal->width) {
405                 if (i % 8 == 0)
406                         terminal->tab_ruler[i] = 1;
407                 else
408                         terminal->tab_ruler[i] = 0;
409                 i++;
410         }
411 }
412
413 static void
414 terminal_init(struct terminal *terminal)
415 {
416         terminal->curr_attr = terminal->color_scheme->default_attr;
417         terminal->origin_mode = 0;
418         terminal->mode = MODE_SHOW_CURSOR |
419                          MODE_AUTOREPEAT |
420                          MODE_ALT_SENDS_ESC |
421                          MODE_AUTOWRAP;
422
423         terminal->row = 0;
424         terminal->column = 0;
425
426         terminal->g0 = CS_US;
427         terminal->g1 = CS_US;
428         terminal->cs = terminal->g0;
429         terminal->key_mode = KM_NORMAL;
430
431         terminal->saved_g0 = terminal->g0;
432         terminal->saved_g1 = terminal->g1;
433         terminal->saved_cs = terminal->cs;
434
435         terminal->saved_attr = terminal->curr_attr;
436         terminal->saved_origin_mode = terminal->origin_mode;
437         terminal->saved_row = terminal->row;
438         terminal->saved_column = terminal->column;
439
440         if (terminal->tab_ruler != NULL) terminal_init_tabs(terminal);
441 }
442
443 static void
444 init_color_table(struct terminal *terminal)
445 {
446         int c, r;
447         struct terminal_color *color_table = terminal->color_table;
448
449         for (c = 0; c < 256; c ++) {
450                 if (c < 16) {
451                         color_table[c] = terminal->color_scheme->palette[c];
452                 } else if (c < 232) {
453                         r = c - 16;
454                         color_table[c].b = ((double)(r % 6) / 6.0); r /= 6;
455                         color_table[c].g = ((double)(r % 6) / 6.0); r /= 6;
456                         color_table[c].r = ((double)(r % 6) / 6.0);
457                         color_table[c].a = 1.0;
458                 } else {
459                         r = (c - 232) * 10 + 8;
460                         color_table[c].r = ((double) r) / 256.0;
461                         color_table[c].g = color_table[c].r;
462                         color_table[c].b = color_table[c].r;
463                         color_table[c].a = 1.0;
464                 }
465         }
466 }
467
468 static union utf8_char *
469 terminal_get_row(struct terminal *terminal, int row)
470 {
471         int index;
472
473         index = (row + terminal->start) % terminal->height;
474
475         return &terminal->data[index * terminal->width];
476 }
477
478 static struct attr*
479 terminal_get_attr_row(struct terminal *terminal, int row)
480 {
481         int index;
482
483         index = (row + terminal->start) % terminal->height;
484
485         return &terminal->data_attr[index * terminal->width];
486 }
487
488 union decoded_attr {
489         struct attr attr;
490         uint32_t key;
491 };
492
493 static int
494 terminal_compare_position(struct terminal *terminal,
495                           int x, int y, int32_t ref_row, int32_t ref_col)
496 {
497         struct rectangle allocation;
498         int top_margin, side_margin, col, row, ref_x;
499
500         widget_get_allocation(terminal->widget, &allocation);
501         side_margin = allocation.x + (allocation.width - terminal->width * terminal->extents.max_x_advance) / 2;
502         top_margin = allocation.y + (allocation.height - terminal->height * terminal->extents.height) / 2;
503
504         col = (x - side_margin) / terminal->extents.max_x_advance;
505         row = (y - top_margin) / terminal->extents.height;
506
507         ref_x = side_margin + ref_col * terminal->extents.max_x_advance +
508                 terminal->extents.max_x_advance / 2;
509
510         if (row < ref_row)
511                 return -1;
512         if (row == ref_row) {
513                 if (col < ref_col)
514                         return -1;
515                 if (col == ref_col && x < ref_x)
516                         return -1;
517         }
518
519         return 1;
520 }
521
522 static void
523 terminal_decode_attr(struct terminal *terminal, int row, int col,
524                      union decoded_attr *decoded)
525 {
526         struct attr attr;
527         int foreground, background, tmp;
528         int start_cmp, end_cmp;
529
530         start_cmp =
531                 terminal_compare_position(terminal,
532                                           terminal->selection_start_x,
533                                           terminal->selection_start_y,
534                                           row, col);
535         end_cmp =
536                 terminal_compare_position(terminal,
537                                           terminal->selection_end_x,
538                                           terminal->selection_end_y,
539                                           row, col);
540         decoded->attr.s = 0;
541         if (start_cmp < 0 && end_cmp > 0)
542                 decoded->attr.s = 1;
543         else if (end_cmp < 0 && start_cmp > 0)
544                 decoded->attr.s = 1;
545
546         /* get the attributes for this character cell */
547         attr = terminal_get_attr_row(terminal, row)[col];
548         if ((attr.a & ATTRMASK_INVERSE) ||
549             decoded->attr.s ||
550             ((terminal->mode & MODE_SHOW_CURSOR) &&
551              terminal->focused && terminal->row == row &&
552              terminal->column == col)) {
553                 foreground = attr.bg;
554                 background = attr.fg;
555                 if (attr.a & ATTRMASK_BOLD) {
556                         if (foreground <= 16) foreground |= 0x08;
557                         if (background <= 16) background &= 0x07;
558                 }
559         } else {
560                 foreground = attr.fg;
561                 background = attr.bg;
562         }
563
564         if (terminal->mode & MODE_INVERSE) {
565                 tmp = foreground;
566                 foreground = background;
567                 background = tmp;
568                 if (attr.a & ATTRMASK_BOLD) {
569                         if (foreground <= 16) foreground |= 0x08;
570                         if (background <= 16) background &= 0x07;
571                 }
572         }
573
574         decoded->attr.fg = foreground;
575         decoded->attr.bg = background;
576         decoded->attr.a = attr.a;
577 }
578
579
580 static void
581 terminal_scroll_buffer(struct terminal *terminal, int d)
582 {
583         int i;
584
585         d = d % (terminal->height + 1);
586         terminal->start = (terminal->start + d) % terminal->height;
587         if (terminal->start < 0) terminal->start = terminal->height + terminal->start;
588         if(d < 0) {
589                 d = 0 - d;
590                 for(i = 0; i < d; i++) {
591                         memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
592                         attr_init(terminal_get_attr_row(terminal, i),
593                             terminal->curr_attr, terminal->width);
594                 }
595         } else {
596                 for(i = terminal->height - d; i < terminal->height; i++) {
597                         memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
598                         attr_init(terminal_get_attr_row(terminal, i),
599                             terminal->curr_attr, terminal->width);
600                 }
601         }
602 }
603
604 static void
605 terminal_scroll_window(struct terminal *terminal, int d)
606 {
607         int i;
608         int window_height;
609         int from_row, to_row;
610         
611         // scrolling range is inclusive
612         window_height = terminal->margin_bottom - terminal->margin_top + 1;
613         d = d % (window_height + 1);
614         if(d < 0) {
615                 d = 0 - d;
616                 to_row = terminal->margin_bottom;
617                 from_row = terminal->margin_bottom - d;
618                 
619                 for (i = 0; i < (window_height - d); i++) {
620                         memcpy(terminal_get_row(terminal, to_row - i),
621                                terminal_get_row(terminal, from_row - i),
622                                terminal->data_pitch);
623                         memcpy(terminal_get_attr_row(terminal, to_row - i),
624                                terminal_get_attr_row(terminal, from_row - i),
625                                terminal->attr_pitch);
626                 }
627                 for (i = terminal->margin_top; i < (terminal->margin_top + d); i++) {
628                         memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
629                         attr_init(terminal_get_attr_row(terminal, i),
630                                 terminal->curr_attr, terminal->width);
631                 }
632         } else {
633                 to_row = terminal->margin_top;
634                 from_row = terminal->margin_top + d;
635                 
636                 for (i = 0; i < (window_height - d); i++) {
637                         memcpy(terminal_get_row(terminal, to_row + i),
638                                terminal_get_row(terminal, from_row + i),
639                                terminal->data_pitch);
640                         memcpy(terminal_get_attr_row(terminal, to_row + i),
641                                terminal_get_attr_row(terminal, from_row + i),
642                                terminal->attr_pitch);
643                 }
644                 for (i = terminal->margin_bottom - d + 1; i <= terminal->margin_bottom; i++) {
645                         memset(terminal_get_row(terminal, i), 0, terminal->data_pitch);
646                         attr_init(terminal_get_attr_row(terminal, i),
647                                 terminal->curr_attr, terminal->width);
648                 }
649         }
650 }
651
652 static void
653 terminal_scroll(struct terminal *terminal, int d)
654 {
655         if(terminal->margin_top == 0 && terminal->margin_bottom == terminal->height - 1)
656                 terminal_scroll_buffer(terminal, d);
657         else
658                 terminal_scroll_window(terminal, d);
659 }
660
661 static void
662 terminal_shift_line(struct terminal *terminal, int d)
663 {
664         union utf8_char *row;
665         struct attr *attr_row;
666         
667         row = terminal_get_row(terminal, terminal->row);
668         attr_row = terminal_get_attr_row(terminal, terminal->row);
669
670         if ((terminal->width + d) <= terminal->column)
671                 d = terminal->column + 1 - terminal->width;
672         if ((terminal->column + d) >= terminal->width)
673                 d = terminal->width - terminal->column - 1;
674         
675         if (d < 0) {
676                 d = 0 - d;
677                 memmove(&row[terminal->column],
678                         &row[terminal->column + d],
679                         (terminal->width - terminal->column - d) * sizeof(union utf8_char));
680                 memmove(&attr_row[terminal->column], &attr_row[terminal->column + d],
681                         (terminal->width - terminal->column - d) * sizeof(struct attr));
682                 memset(&row[terminal->width - d], 0, d * sizeof(union utf8_char));
683                 attr_init(&attr_row[terminal->width - d], terminal->curr_attr, d);
684         } else {
685                 memmove(&row[terminal->column + d], &row[terminal->column],
686                         (terminal->width - terminal->column - d) * sizeof(union utf8_char));
687                 memmove(&attr_row[terminal->column + d], &attr_row[terminal->column],
688                         (terminal->width - terminal->column - d) * sizeof(struct attr));
689                 memset(&row[terminal->column], 0, d * sizeof(union utf8_char));
690                 attr_init(&attr_row[terminal->column], terminal->curr_attr, d);
691         }
692 }
693
694 static void
695 terminal_resize_cells(struct terminal *terminal, int width, int height)
696 {
697         size_t size;
698         union utf8_char *data;
699         struct attr *data_attr;
700         char *tab_ruler;
701         int data_pitch, attr_pitch;
702         int i, l, total_rows;
703         struct rectangle allocation;
704         struct winsize ws;
705
706         if (width < 1)
707                 width = 1;
708         if (height < 1)
709                 height = 1;
710         if (terminal->width == width && terminal->height == height)
711                 return;
712
713         data_pitch = width * sizeof(union utf8_char);
714         size = data_pitch * height;
715         data = malloc(size);
716         attr_pitch = width * sizeof(struct attr);
717         data_attr = malloc(attr_pitch * height);
718         tab_ruler = malloc(width);
719         memset(data, 0, size);
720         memset(tab_ruler, 0, width);
721         attr_init(data_attr, terminal->curr_attr, width * height);
722         if (terminal->data && terminal->data_attr) {
723                 if (width > terminal->width)
724                         l = terminal->width;
725                 else
726                         l = width;
727
728                 if (terminal->height > height) {
729                         total_rows = height;
730                 } else {
731                         total_rows = terminal->height;
732                 }
733
734                 for (i = 0; i < total_rows; i++) {
735                         memcpy(&data[width * i],
736                                terminal_get_row(terminal, i),
737                                l * sizeof(union utf8_char));
738                         memcpy(&data_attr[width * i],
739                                terminal_get_attr_row(terminal, i),
740                                l * sizeof(struct attr));
741                 }
742
743                 free(terminal->data);
744                 free(terminal->data_attr);
745                 free(terminal->tab_ruler);
746         }
747
748         terminal->data_pitch = data_pitch;
749         terminal->attr_pitch = attr_pitch;
750         terminal->margin_bottom =
751                 height - (terminal->height - terminal->margin_bottom);
752         terminal->width = width;
753         terminal->height = height;
754         terminal->data = data;
755         terminal->data_attr = data_attr;
756         terminal->tab_ruler = tab_ruler;
757         terminal_init_tabs(terminal);
758
759         /* Update the window size */
760         ws.ws_row = terminal->height;
761         ws.ws_col = terminal->width;
762         widget_get_allocation(terminal->widget, &allocation);
763         ws.ws_xpixel = allocation.width;
764         ws.ws_ypixel = allocation.height;
765         ioctl(terminal->master, TIOCSWINSZ, &ws);
766 }
767
768 static void
769 resize_handler(struct widget *widget,
770                int32_t width, int32_t height, void *data)
771 {
772         struct terminal *terminal = data;
773         int32_t columns, rows, m;
774
775     if (width < 200)
776         width = 200;
777
778     if (height < 50)
779         height = 50;
780
781         m = 2 * terminal->margin;
782         columns = (width - m) / (int32_t) terminal->extents.max_x_advance;
783         rows = (height - m) / (int32_t) terminal->extents.height;
784
785         if (!terminal->fullscreen) {
786                 width = columns * terminal->extents.max_x_advance + m;
787                 height = rows * terminal->extents.height + m;
788                 widget_set_size(terminal->widget, width, height);
789         }
790
791         terminal_resize_cells(terminal, columns, rows);
792 }
793
794 static void
795 terminal_resize(struct terminal *terminal, int columns, int rows)
796 {
797         int32_t width, height, m;
798
799         if (terminal->fullscreen)
800                 return;
801
802         m = 2 * terminal->margin;
803         width = columns * terminal->extents.max_x_advance + m;
804         height = rows * terminal->extents.height + m;
805         widget_schedule_resize(terminal->widget, width, height);
806 }
807
808 struct color_scheme DEFAULT_COLORS = {
809         {
810                 {0,    0,    0,    1}, /* black */
811                 {0.66, 0,    0,    1}, /* red */
812                 {0  ,  0.66, 0,    1}, /* green */
813                 {0.66, 0.33, 0,    1}, /* orange (nicer than muddy yellow) */
814                 {0  ,  0  ,  0.66, 1}, /* blue */
815                 {0.66, 0  ,  0.66, 1}, /* magenta */
816                 {0,    0.66, 0.66, 1}, /* cyan */
817                 {0.66, 0.66, 0.66, 1}, /* light grey */
818                 {0.22, 0.33, 0.33, 1}, /* dark grey */
819                 {1,    0.33, 0.33, 1}, /* high red */
820                 {0.33, 1,    0.33, 1}, /* high green */
821                 {1,    1,    0.33, 1}, /* high yellow */
822                 {0.33, 0.33, 1,    1}, /* high blue */
823                 {1,    0.33, 1,    1}, /* high magenta */
824                 {0.33, 1,    1,    1}, /* high cyan */
825                 {1,    1,    1,    1}  /* white */
826         },
827         0,                             /* black border */
828         {7, 0, 0, }                    /* bg:black (0), fg:light gray (7)  */
829 };
830
831 static void
832 terminal_set_color(struct terminal *terminal, cairo_t *cr, int index)
833 {
834         cairo_set_source_rgba(cr,
835                               terminal->color_table[index].r,
836                               terminal->color_table[index].g,
837                               terminal->color_table[index].b,
838                               terminal->color_table[index].a);
839 }
840
841 static void
842 terminal_send_selection(struct terminal *terminal, int fd)
843 {
844         int row, col;
845         union utf8_char *p_row;
846         union decoded_attr attr;
847         FILE *fp;
848         int len;
849
850         fp = fdopen(fd, "w");
851         for (row = 0; row < terminal->height; row++) {
852                 p_row = terminal_get_row(terminal, row);
853                 for (col = 0; col < terminal->width; col++) {
854                         /* get the attributes for this character cell */
855                         terminal_decode_attr(terminal, row, col, &attr);
856                         if (!attr.attr.s)
857                                 continue;
858                         len = strnlen((char *) p_row[col].byte, 4);
859                         fwrite(p_row[col].byte, 1, len, fp);
860                 }
861         }
862         fclose(fp);
863 }
864
865 struct glyph_run {
866         struct terminal *terminal;
867         cairo_t *cr;
868         unsigned int count;
869         union decoded_attr attr;
870         cairo_glyph_t glyphs[256], *g;
871 };
872
873 static void
874 glyph_run_init(struct glyph_run *run, struct terminal *terminal, cairo_t *cr)
875 {
876         run->terminal = terminal;
877         run->cr = cr;
878         run->g = run->glyphs;
879         run->count = 0;
880         run->attr.key = 0;
881 }
882
883 static void
884 glyph_run_flush(struct glyph_run *run, union decoded_attr attr)
885 {
886         cairo_scaled_font_t *font;
887
888         if (run->count > ARRAY_LENGTH(run->glyphs) - 10 ||
889             (attr.key != run->attr.key)) {
890                 if (run->attr.attr.a & (ATTRMASK_BOLD | ATTRMASK_BLINK))
891                         font = run->terminal->font_bold;
892                 else
893                         font = run->terminal->font_normal;
894                 cairo_set_scaled_font(run->cr, font);
895                 terminal_set_color(run->terminal, run->cr,
896                                    run->attr.attr.fg);
897
898                 if (!(run->attr.attr.a & ATTRMASK_CONCEALED))
899                         cairo_show_glyphs (run->cr, run->glyphs, run->count);
900                 run->g = run->glyphs;
901                 run->count = 0;
902         }
903         run->attr = attr;
904 }
905
906 static void
907 glyph_run_add(struct glyph_run *run, int x, int y, union utf8_char *c)
908 {
909         int num_glyphs;
910         cairo_scaled_font_t *font;
911
912         num_glyphs = ARRAY_LENGTH(run->glyphs) - run->count;
913
914         if (run->attr.attr.a & (ATTRMASK_BOLD | ATTRMASK_BLINK))
915                 font = run->terminal->font_bold;
916         else
917                 font = run->terminal->font_normal;
918
919         cairo_move_to(run->cr, x, y);
920         cairo_scaled_font_text_to_glyphs (font, x, y,
921                                           (char *) c->byte, 4,
922                                           &run->g, &num_glyphs,
923                                           NULL, NULL, NULL);
924         run->g += num_glyphs;
925         run->count += num_glyphs;
926 }
927
928
929 static void
930 redraw_handler(struct widget *widget, void *data)
931 {
932         struct terminal *terminal = data;
933         struct rectangle allocation;
934         cairo_t *cr;
935         int top_margin, side_margin;
936         int row, col, cursor_x, cursor_y;
937         union utf8_char *p_row;
938         union decoded_attr attr;
939         int text_x, text_y;
940         cairo_surface_t *surface;
941         double d;
942         struct glyph_run run;
943         cairo_font_extents_t extents;
944
945         surface = window_get_surface(terminal->window);
946         widget_get_allocation(terminal->widget, &allocation);
947         cr = cairo_create(surface);
948         cairo_rectangle(cr, allocation.x, allocation.y,
949                         allocation.width, allocation.height);
950         cairo_clip(cr);
951         cairo_push_group(cr);
952
953         cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
954         terminal_set_color(terminal, cr, terminal->color_scheme->border);
955         cairo_paint(cr);
956
957         cairo_set_scaled_font(cr, terminal->font_normal);
958
959         extents = terminal->extents;
960         side_margin = (allocation.width - terminal->width * extents.max_x_advance) / 2;
961         top_margin = (allocation.height - terminal->height * extents.height) / 2;
962
963         cairo_set_line_width(cr, 1.0);
964         cairo_translate(cr, allocation.x + side_margin,
965                         allocation.y + top_margin);
966         /* paint the background */
967         for (row = 0; row < terminal->height; row++) {
968                 for (col = 0; col < terminal->width; col++) {
969                         /* get the attributes for this character cell */
970                         terminal_decode_attr(terminal, row, col, &attr);
971
972                         if (attr.attr.bg == terminal->color_scheme->border)
973                                 continue;
974
975                         terminal_set_color(terminal, cr, attr.attr.bg);
976                         cairo_move_to(cr, col * extents.max_x_advance,
977                                       row * extents.height);
978                         cairo_rel_line_to(cr, extents.max_x_advance, 0);
979                         cairo_rel_line_to(cr, 0, extents.height);
980                         cairo_rel_line_to(cr, -extents.max_x_advance, 0);
981                         cairo_close_path(cr);
982                         cairo_fill(cr);
983                 }
984         }
985
986         cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
987
988         /* paint the foreground */
989         glyph_run_init(&run, terminal, cr);
990         for (row = 0; row < terminal->height; row++) {
991                 p_row = terminal_get_row(terminal, row);
992                 for (col = 0; col < terminal->width; col++) {
993                         /* get the attributes for this character cell */
994                         terminal_decode_attr(terminal, row, col, &attr);
995
996                         glyph_run_flush(&run, attr);
997
998                         text_x = col * extents.max_x_advance;
999                         text_y = extents.ascent + row * extents.height;
1000                         if (attr.attr.a & ATTRMASK_UNDERLINE) {
1001                                 terminal_set_color(terminal, cr, attr.attr.fg);
1002                                 cairo_move_to(cr, text_x, (double)text_y + 1.5);
1003                                 cairo_line_to(cr, text_x + extents.max_x_advance, (double) text_y + 1.5);
1004                                 cairo_stroke(cr);
1005                         }
1006
1007                         glyph_run_add(&run, text_x, text_y, &p_row[col]);
1008                 }
1009         }
1010
1011         attr.key = ~0;
1012         glyph_run_flush(&run, attr);
1013
1014         if ((terminal->mode & MODE_SHOW_CURSOR) && !terminal->focused) {
1015                 d = 0.5;
1016
1017                 cairo_set_line_width(cr, 1);
1018                 cairo_move_to(cr, terminal->column * extents.max_x_advance + d,
1019                               terminal->row * extents.height + d);
1020                 cairo_rel_line_to(cr, extents.max_x_advance - 2 * d, 0);
1021                 cairo_rel_line_to(cr, 0, extents.height - 2 * d);
1022                 cairo_rel_line_to(cr, -extents.max_x_advance + 2 * d, 0);
1023                 cairo_close_path(cr);
1024
1025                 cairo_stroke(cr);
1026         }
1027
1028         cairo_pop_group_to_source(cr);
1029         cairo_paint(cr);
1030         cairo_destroy(cr);
1031         cairo_surface_destroy(surface);
1032
1033         if (terminal->send_cursor_position) {
1034                 cursor_x = side_margin + allocation.x +
1035                                 terminal->column * extents.max_x_advance;
1036                 cursor_y = top_margin + allocation.y +
1037                                 terminal->row * extents.height;
1038                 window_set_text_cursor_position(terminal->window,
1039                                                 cursor_x, cursor_y);
1040                 terminal->send_cursor_position = 0;
1041         }
1042 }
1043
1044 static void
1045 terminal_write(struct terminal *terminal, const char *data, size_t length)
1046 {
1047         if (write(terminal->master, data, length) < 0)
1048                 abort();
1049         terminal->send_cursor_position = 1;
1050 }
1051
1052 static void
1053 terminal_data(struct terminal *terminal, const char *data, size_t length);
1054
1055 static void
1056 handle_char(struct terminal *terminal, union utf8_char utf8);
1057
1058 static void
1059 handle_sgr(struct terminal *terminal, int code);
1060
1061 static void
1062 handle_term_parameter(struct terminal *terminal, int code, int sr)
1063 {
1064         int i;
1065
1066         if (terminal->escape_flags & ESC_FLAG_WHAT) {
1067                 switch(code) {
1068                 case 1:  /* DECCKM */
1069                         if (sr) terminal->key_mode = KM_APPLICATION;
1070                         else    terminal->key_mode = KM_NORMAL;
1071                         break;
1072                 case 2:  /* DECANM */
1073                         /* No VT52 support yet */
1074                         terminal->g0 = CS_US;
1075                         terminal->g1 = CS_US;
1076                         terminal->cs = terminal->g0;
1077                         break;
1078                 case 3:  /* DECCOLM */
1079                         if (sr)
1080                                 terminal_resize(terminal, 132, 24);
1081                         else
1082                                 terminal_resize(terminal, 80, 24);
1083                         
1084                         /* set columns, but also home cursor and clear screen */
1085                         terminal->row = 0; terminal->column = 0;
1086                         for (i = 0; i < terminal->height; i++) {
1087                                 memset(terminal_get_row(terminal, i),
1088                                     0, terminal->data_pitch);
1089                                 attr_init(terminal_get_attr_row(terminal, i),
1090                                     terminal->curr_attr, terminal->width);
1091                         }
1092                         break;
1093                 case 5:  /* DECSCNM */
1094                         if (sr) terminal->mode |=  MODE_INVERSE;
1095                         else    terminal->mode &= ~MODE_INVERSE;
1096                         break;
1097                 case 6:  /* DECOM */
1098                         terminal->origin_mode = sr;
1099                         if (terminal->origin_mode)
1100                                 terminal->row = terminal->margin_top;
1101                         else
1102                                 terminal->row = 0;
1103                         terminal->column = 0;
1104                         break;
1105                 case 7:  /* DECAWM */
1106                         if (sr) terminal->mode |=  MODE_AUTOWRAP;
1107                         else    terminal->mode &= ~MODE_AUTOWRAP;
1108                         break;
1109                 case 8:  /* DECARM */
1110                         if (sr) terminal->mode |=  MODE_AUTOREPEAT;
1111                         else    terminal->mode &= ~MODE_AUTOREPEAT;
1112                         break;
1113                 case 25:
1114                         if (sr) terminal->mode |=  MODE_SHOW_CURSOR;
1115                         else    terminal->mode &= ~MODE_SHOW_CURSOR;
1116                         break;
1117                 case 1037:   /* deleteSendsDel */
1118                         if (sr) terminal->mode |=  MODE_DELETE_SENDS_DEL;
1119                         else    terminal->mode &= ~MODE_DELETE_SENDS_DEL;
1120                         break;
1121                 case 1039:   /* altSendsEscape */
1122                         if (sr) terminal->mode |=  MODE_ALT_SENDS_ESC;
1123                         else    terminal->mode &= ~MODE_ALT_SENDS_ESC;
1124                         break;
1125                 default:
1126                         fprintf(stderr, "Unknown parameter: ?%d\n", code);
1127                         break;
1128                 }
1129         } else {
1130                 switch(code) {
1131                 case 4:  /* IRM */
1132                         if (sr) terminal->mode |=  MODE_IRM;
1133                         else    terminal->mode &= ~MODE_IRM;
1134                         break;
1135                 case 20: /* LNM */
1136                         if (sr) terminal->mode |=  MODE_LF_NEWLINE;
1137                         else    terminal->mode &= ~MODE_LF_NEWLINE;
1138                         break;
1139                 default:
1140                         fprintf(stderr, "Unknown parameter: %d\n", code);
1141                         break;
1142                 }
1143         }
1144 }
1145
1146 static void
1147 handle_dcs(struct terminal *terminal)
1148 {
1149 }
1150
1151 static void
1152 handle_osc(struct terminal *terminal)
1153 {
1154         char *p;
1155         int code;
1156
1157         terminal->escape[terminal->escape_length++] = '\0';
1158         p = &terminal->escape[2];
1159         code = strtol(p, &p, 10);
1160         if (*p == ';') p++;
1161
1162         switch (code) {
1163         case 0: /* Icon name and window title */
1164         case 1: /* Icon label */
1165         case 2: /* Window title*/
1166                 window_set_title(terminal->window, p);
1167                 break;
1168         default:
1169                 fprintf(stderr, "Unknown OSC escape code %d\n", code);
1170                 break;
1171         }
1172 }
1173
1174 static void
1175 handle_escape(struct terminal *terminal)
1176 {
1177         union utf8_char *row;
1178         struct attr *attr_row;
1179         char *p;
1180         int i, count, x, y, top, bottom;
1181         int args[10], set[10] = { 0, };
1182         char response[MAX_RESPONSE] = {0, };
1183         struct rectangle allocation;
1184
1185         terminal->escape[terminal->escape_length++] = '\0';
1186         i = 0;
1187         p = &terminal->escape[2];
1188         while ((isdigit(*p) || *p == ';') && i < 10) {
1189                 if (*p == ';') {
1190                         if (!set[i]) {
1191                                 args[i] = 0;
1192                                 set[i] = 1;
1193                         }
1194                         p++;
1195                         i++;
1196                 } else {
1197                         args[i] = strtol(p, &p, 10);
1198                         set[i] = 1;
1199                 }
1200         }
1201         
1202         switch (*p) {
1203         case '@':    /* ICH */
1204                 count = set[0] ? args[0] : 1;
1205                 if (count == 0) count = 1;
1206                 terminal_shift_line(terminal, count);
1207                 break;
1208         case 'A':    /* CUU */
1209                 count = set[0] ? args[0] : 1;
1210                 if (count == 0) count = 1;
1211                 if (terminal->row - count >= terminal->margin_top)
1212                         terminal->row -= count;
1213                 else
1214                         terminal->row = terminal->margin_top;
1215                 break;
1216         case 'B':    /* CUD */
1217                 count = set[0] ? args[0] : 1;
1218                 if (count == 0) count = 1;
1219                 if (terminal->row + count <= terminal->margin_bottom)
1220                         terminal->row += count;
1221                 else
1222                         terminal->row = terminal->margin_bottom;
1223                 break;
1224         case 'C':    /* CUF */
1225                 count = set[0] ? args[0] : 1;
1226                 if (count == 0) count = 1;
1227                 if ((terminal->column + count) < terminal->width)
1228                         terminal->column += count;
1229                 else
1230                         terminal->column = terminal->width - 1;
1231                 break;
1232         case 'D':    /* CUB */
1233                 count = set[0] ? args[0] : 1;
1234                 if (count == 0) count = 1;
1235                 if ((terminal->column - count) >= 0)
1236                         terminal->column -= count;
1237                 else
1238                         terminal->column = 0;
1239                 break;
1240         case 'E':    /* CNL */
1241                 count = set[0] ? args[0] : 1;
1242                 if (terminal->row + count <= terminal->margin_bottom)
1243                         terminal->row += count;
1244                 else
1245                         terminal->row = terminal->margin_bottom;
1246                 terminal->column = 0;
1247                 break;
1248         case 'F':    /* CPL */
1249                 count = set[0] ? args[0] : 1;
1250                 if (terminal->row - count >= terminal->margin_top)
1251                         terminal->row -= count;
1252                 else
1253                         terminal->row = terminal->margin_top;
1254                 terminal->column = 0;
1255                 break;
1256         case 'G':    /* CHA */
1257                 y = set[0] ? args[0] : 1;
1258                 y = y <= 0 ? 1 : y > terminal->width ? terminal->width : y;
1259                 
1260                 terminal->column = y - 1;
1261                 break;
1262         case 'f':    /* HVP */
1263         case 'H':    /* CUP */
1264                 x = (set[1] ? args[1] : 1) - 1;
1265                 x = x < 0 ? 0 :
1266                     (x >= terminal->width ? terminal->width - 1 : x);
1267                 
1268                 y = (set[0] ? args[0] : 1) - 1;
1269                 if (terminal->origin_mode) {
1270                         y += terminal->margin_top;
1271                         y = y < terminal->margin_top ? terminal->margin_top :
1272                             (y > terminal->margin_bottom ? terminal->margin_bottom : y);
1273                 } else {
1274                         y = y < 0 ? 0 :
1275                             (y >= terminal->height ? terminal->height - 1 : y);
1276                 }
1277                 
1278                 terminal->row = y;
1279                 terminal->column = x;
1280                 break;
1281         case 'I':    /* CHT */
1282                 count = set[0] ? args[0] : 1;
1283                 if (count == 0) count = 1;
1284                 while (count > 0 && terminal->column < terminal->width) {
1285                         if (terminal->tab_ruler[terminal->column]) count--;
1286                         terminal->column++;
1287                 }
1288                 terminal->column--;
1289                 break;
1290         case 'J':    /* ED */
1291                 row = terminal_get_row(terminal, terminal->row);
1292                 attr_row = terminal_get_attr_row(terminal, terminal->row);
1293                 if (!set[0] || args[0] == 0 || args[0] > 2) {
1294                         memset(&row[terminal->column],
1295                                0, (terminal->width - terminal->column) * sizeof(union utf8_char));
1296                         attr_init(&attr_row[terminal->column],
1297                                terminal->curr_attr, terminal->width - terminal->column);
1298                         for (i = terminal->row + 1; i < terminal->height; i++) {
1299                                 memset(terminal_get_row(terminal, i),
1300                                     0, terminal->data_pitch);
1301                                 attr_init(terminal_get_attr_row(terminal, i),
1302                                     terminal->curr_attr, terminal->width);
1303                         }
1304                 } else if (args[0] == 1) {
1305                         memset(row, 0, (terminal->column+1) * sizeof(union utf8_char));
1306                         attr_init(attr_row, terminal->curr_attr, terminal->column+1);
1307                         for (i = 0; i < terminal->row; i++) {
1308                                 memset(terminal_get_row(terminal, i),
1309                                     0, terminal->data_pitch);
1310                                 attr_init(terminal_get_attr_row(terminal, i),
1311                                     terminal->curr_attr, terminal->width);
1312                         }
1313                 } else if (args[0] == 2) {
1314                         for (i = 0; i < terminal->height; i++) {
1315                                 memset(terminal_get_row(terminal, i),
1316                                     0, terminal->data_pitch);
1317                                 attr_init(terminal_get_attr_row(terminal, i),
1318                                     terminal->curr_attr, terminal->width);
1319                         }
1320                 }
1321                 break;
1322         case 'K':    /* EL */
1323                 row = terminal_get_row(terminal, terminal->row);
1324                 attr_row = terminal_get_attr_row(terminal, terminal->row);
1325                 if (!set[0] || args[0] == 0 || args[0] > 2) {
1326                         memset(&row[terminal->column], 0,
1327                             (terminal->width - terminal->column) * sizeof(union utf8_char));
1328                         attr_init(&attr_row[terminal->column], terminal->curr_attr,
1329                             terminal->width - terminal->column);
1330                 } else if (args[0] == 1) {
1331                         memset(row, 0, (terminal->column+1) * sizeof(union utf8_char));
1332                         attr_init(attr_row, terminal->curr_attr, terminal->column+1);
1333                 } else if (args[0] == 2) {
1334                         memset(row, 0, terminal->data_pitch);
1335                         attr_init(attr_row, terminal->curr_attr, terminal->width);
1336                 }
1337                 break;
1338         case 'L':    /* IL */
1339                 count = set[0] ? args[0] : 1;
1340                 if (count == 0) count = 1;
1341                 if (terminal->row >= terminal->margin_top &&
1342                         terminal->row < terminal->margin_bottom)
1343                 {
1344                         top = terminal->margin_top;
1345                         terminal->margin_top = terminal->row;
1346                         terminal_scroll(terminal, 0 - count);
1347                         terminal->margin_top = top;
1348                 } else if (terminal->row == terminal->margin_bottom) {
1349                         memset(terminal_get_row(terminal, terminal->row),
1350                                0, terminal->data_pitch);
1351                         attr_init(terminal_get_attr_row(terminal, terminal->row),
1352                                 terminal->curr_attr, terminal->width);
1353                 }
1354                 break;
1355         case 'M':    /* DL */
1356                 count = set[0] ? args[0] : 1;
1357                 if (count == 0) count = 1;
1358                 if (terminal->row >= terminal->margin_top &&
1359                         terminal->row < terminal->margin_bottom)
1360                 {
1361                         top = terminal->margin_top;
1362                         terminal->margin_top = terminal->row;
1363                         terminal_scroll(terminal, count);
1364                         terminal->margin_top = top;
1365                 } else if (terminal->row == terminal->margin_bottom) {
1366                         memset(terminal_get_row(terminal, terminal->row),
1367                                0, terminal->data_pitch);
1368                 }
1369                 break;
1370         case 'P':    /* DCH */
1371                 count = set[0] ? args[0] : 1;
1372                 if (count == 0) count = 1;
1373                 terminal_shift_line(terminal, 0 - count);
1374                 break;
1375         case 'S':    /* SU */
1376                 terminal_scroll(terminal, set[0] ? args[0] : 1);
1377                 break;
1378         case 'T':    /* SD */
1379                 terminal_scroll(terminal, 0 - (set[0] ? args[0] : 1));
1380                 break;
1381         case 'X':    /* ECH */
1382                 count = set[0] ? args[0] : 1;
1383                 if (count == 0) count = 1;
1384                 if ((terminal->column + count) > terminal->width)
1385                         count = terminal->width - terminal->column;
1386                 row = terminal_get_row(terminal, terminal->row);
1387                 attr_row = terminal_get_attr_row(terminal, terminal->row);
1388                 memset(&row[terminal->column], 0, count * sizeof(union utf8_char));
1389                 attr_init(&attr_row[terminal->column], terminal->curr_attr, count);
1390                 break;
1391         case 'Z':    /* CBT */
1392                 count = set[0] ? args[0] : 1;
1393                 if (count == 0) count = 1;
1394                 while (count > 0 && terminal->column >= 0) {
1395                         if (terminal->tab_ruler[terminal->column]) count--;
1396                         terminal->column--;
1397                 }
1398                 terminal->column++;
1399                 break;
1400         case '`':    /* HPA */
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 'b':    /* REP */
1407                 count = set[0] ? args[0] : 1;
1408                 if (count == 0) count = 1;
1409                 if (terminal->last_char.byte[0])
1410                         for (i = 0; i < count; i++)
1411                                 handle_char(terminal, terminal->last_char);
1412                 terminal->last_char.byte[0] = 0;
1413                 break;
1414         case 'c':    /* Primary DA */
1415                 terminal_write(terminal, "\e[?6c", 5);
1416                 break;
1417         case 'd':    /* VPA */
1418                 x = set[0] ? args[0] : 1;
1419                 x = x <= 0 ? 1 : x > terminal->height ? terminal->height : x;
1420                 
1421                 terminal->row = x - 1;
1422                 break;
1423         case 'g':    /* TBC */
1424                 if (!set[0] || args[0] == 0) {
1425                         terminal->tab_ruler[terminal->column] = 0;
1426                 } else if (args[0] == 3) {
1427                         memset(terminal->tab_ruler, 0, terminal->width);
1428                 }
1429                 break;
1430         case 'h':    /* SM */
1431                 for(i = 0; i < 10 && set[i]; i++) {
1432                         handle_term_parameter(terminal, args[i], 1);
1433                 }
1434                 break;
1435         case 'l':    /* RM */
1436                 for(i = 0; i < 10 && set[i]; i++) {
1437                         handle_term_parameter(terminal, args[i], 0);
1438                 }
1439                 break;
1440         case 'm':    /* SGR */
1441                 for(i = 0; i < 10; i++) {
1442                         if (i <= 7 && set[i] && set[i + 1] &&
1443                                 set[i + 2] && args[i + 1] == 5)
1444                         {
1445                                 if (args[i] == 38) {
1446                                         handle_sgr(terminal, args[i + 2] + 256);
1447                                         break;
1448                                 } else if (args[i] == 48) {
1449                                         handle_sgr(terminal, args[i + 2] + 512);
1450                                         break;
1451                                 }
1452                         }
1453                         if(set[i]) {
1454                                 handle_sgr(terminal, args[i]);
1455                         } else if(i == 0) {
1456                                 handle_sgr(terminal, 0);
1457                                 break;
1458                         } else {
1459                                 break;
1460                         }
1461                 }
1462                 break;
1463         case 'n':    /* DSR */
1464                 i = set[0] ? args[0] : 0;
1465                 if (i == 0 || i == 5) {
1466                         terminal_write(terminal, "\e[0n", 4);
1467                 } else if (i == 6) {
1468                         snprintf(response, MAX_RESPONSE, "\e[%d;%dR",
1469                                  terminal->origin_mode ?
1470                                      terminal->row+terminal->margin_top : terminal->row+1,
1471                                  terminal->column+1);
1472                         terminal_write(terminal, response, strlen(response));
1473                 }
1474                 break;
1475         case 'r':
1476                 if(!set[0]) {
1477                         terminal->margin_top = 0;
1478                         terminal->margin_bottom = terminal->height-1;
1479                         terminal->row = 0;
1480                         terminal->column = 0;
1481                 } else {
1482                         top = (set[0] ? args[0] : 1) - 1;
1483                         top = top < 0 ? 0 :
1484                               (top >= terminal->height ? terminal->height - 1 : top);
1485                         bottom = (set[1] ? args[1] : 1) - 1;
1486                         bottom = bottom < 0 ? 0 :
1487                                  (bottom >= terminal->height ? terminal->height - 1 : bottom);
1488                         if(bottom > top) {
1489                                 terminal->margin_top = top;
1490                                 terminal->margin_bottom = bottom;
1491                         } else {
1492                                 terminal->margin_top = 0;
1493                                 terminal->margin_bottom = terminal->height-1;
1494                         }
1495                         if(terminal->origin_mode)
1496                                 terminal->row = terminal->margin_top;
1497                         else
1498                                 terminal->row = 0;
1499                         terminal->column = 0;
1500                 }
1501                 break;
1502         case 's':
1503                 terminal->saved_row = terminal->row;
1504                 terminal->saved_column = terminal->column;
1505                 break;
1506         case 't':    /* windowOps */
1507                 if (!set[0]) break;
1508                 switch (args[0]) {
1509                 case 4:  /* resize px */
1510                         if (set[1] && set[2]) {
1511                                 widget_schedule_resize(terminal->widget,
1512                                                        args[2], args[1]);
1513                         }
1514                         break;
1515                 case 8:  /* resize ch */
1516                         if (set[1] && set[2]) {
1517                                 terminal_resize(terminal, args[2], args[1]);
1518                         }
1519                         break;
1520                 case 13: /* report position */
1521                         widget_get_allocation(terminal->widget, &allocation);
1522                         snprintf(response, MAX_RESPONSE, "\e[3;%d;%dt",
1523                                  allocation.x, allocation.y);
1524                         terminal_write(terminal, response, strlen(response));
1525                         break;
1526                 case 14: /* report px */
1527                         widget_get_allocation(terminal->widget, &allocation);
1528                         snprintf(response, MAX_RESPONSE, "\e[4;%d;%dt",
1529                                  allocation.height, allocation.width);
1530                         terminal_write(terminal, response, strlen(response));
1531                         break;
1532                 case 18: /* report ch */
1533                         snprintf(response, MAX_RESPONSE, "\e[9;%d;%dt",
1534                                  terminal->height, terminal->width);
1535                         terminal_write(terminal, response, strlen(response));
1536                         break;
1537                 case 21: /* report title */
1538                         snprintf(response, MAX_RESPONSE, "\e]l%s\e\\",
1539                                  window_get_title(terminal->window));
1540                         terminal_write(terminal, response, strlen(response));
1541                         break;
1542                 default:
1543                         if (args[0] >= 24)
1544                                 terminal_resize(terminal, terminal->width, args[0]);
1545                         else
1546                                 fprintf(stderr, "Unimplemented windowOp %d\n", args[0]);
1547                         break;
1548                 }
1549         case 'u':
1550                 terminal->row = terminal->saved_row;
1551                 terminal->column = terminal->saved_column;
1552                 break;
1553         default:
1554                 fprintf(stderr, "Unknown CSI escape: %c\n", *p);
1555                 break;
1556         }       
1557 }
1558
1559 static void
1560 handle_non_csi_escape(struct terminal *terminal, char code)
1561 {
1562         switch(code) {
1563         case 'M':    /* RI */
1564                 terminal->row -= 1;
1565                 if(terminal->row < terminal->margin_top) {
1566                         terminal->row = terminal->margin_top;
1567                         terminal_scroll(terminal, -1);
1568                 }
1569                 break;
1570         case 'E':    /* NEL */
1571                 terminal->column = 0;
1572                 // fallthrough
1573         case 'D':    /* IND */
1574                 terminal->row += 1;
1575                 if(terminal->row > terminal->margin_bottom) {
1576                         terminal->row = terminal->margin_bottom;
1577                         terminal_scroll(terminal, +1);
1578                 }
1579                 break;
1580         case 'c':    /* RIS */
1581                 terminal_init(terminal);
1582                 break;
1583         case 'H':    /* HTS */
1584                 terminal->tab_ruler[terminal->column] = 1;
1585                 break;
1586         case '7':    /* DECSC */
1587                 terminal->saved_row = terminal->row;
1588                 terminal->saved_column = terminal->column;
1589                 terminal->saved_attr = terminal->curr_attr;
1590                 terminal->saved_origin_mode = terminal->origin_mode;
1591                 terminal->saved_cs = terminal->cs;
1592                 terminal->saved_g0 = terminal->g0;
1593                 terminal->saved_g1 = terminal->g1;
1594                 break;
1595         case '8':    /* DECRC */
1596                 terminal->row = terminal->saved_row;
1597                 terminal->column = terminal->saved_column;
1598                 terminal->curr_attr = terminal->saved_attr;
1599                 terminal->origin_mode = terminal->saved_origin_mode;
1600                 terminal->cs = terminal->saved_cs;
1601                 terminal->g0 = terminal->saved_g0;
1602                 terminal->g1 = terminal->saved_g1;
1603                 break;
1604         case '=':    /* DECPAM */
1605                 terminal->key_mode = KM_APPLICATION;
1606                 break;
1607         case '>':    /* DECPNM */
1608                 terminal->key_mode = KM_NORMAL;
1609                 break;
1610         default:
1611                 fprintf(stderr, "Unknown escape code: %c\n", code);
1612                 break;
1613         }
1614 }
1615
1616 static void
1617 handle_special_escape(struct terminal *terminal, char special, char code)
1618 {
1619         int i, numChars;
1620
1621         if (special == '#') {
1622                 switch(code) {
1623                 case '8':
1624                         /* fill with 'E', no cheap way to do this */
1625                         memset(terminal->data, 0, terminal->data_pitch * terminal->height);
1626                         numChars = terminal->width * terminal->height;
1627                         for(i = 0; i < numChars; i++) {
1628                                 terminal->data[i].byte[0] = 'E';
1629                         }
1630                         break;
1631                 default:
1632                         fprintf(stderr, "Unknown HASH escape #%c\n", code);
1633                         break;
1634                 }
1635         } else if (special == '(' || special == ')') {
1636                 switch(code) {
1637                 case '0':
1638                         if (special == '(')
1639                                 terminal->g0 = CS_SPECIAL;
1640                         else
1641                                 terminal->g1 = CS_SPECIAL;
1642                         break;
1643                 case 'A':
1644                         if (special == '(')
1645                                 terminal->g0 = CS_UK;
1646                         else
1647                                 terminal->g1 = CS_UK;
1648                         break;
1649                 case 'B':
1650                         if (special == '(')
1651                                 terminal->g0 = CS_US;
1652                         else
1653                                 terminal->g1 = CS_US;
1654                         break;
1655                 default:
1656                         fprintf(stderr, "Unknown character set %c\n", code);
1657                         break;
1658                 }
1659         } else {
1660                 fprintf(stderr, "Unknown special escape %c%c\n", special, code);
1661         }
1662 }
1663
1664 static void
1665 handle_sgr(struct terminal *terminal, int code)
1666 {
1667         switch(code) {
1668         case 0:
1669                 terminal->curr_attr = terminal->color_scheme->default_attr;
1670                 break;
1671         case 1:
1672                 terminal->curr_attr.a |= ATTRMASK_BOLD;
1673                 if (terminal->curr_attr.fg < 8)
1674                         terminal->curr_attr.fg += 8;
1675                 break;
1676         case 4:
1677                 terminal->curr_attr.a |= ATTRMASK_UNDERLINE;
1678                 break;
1679         case 5:
1680                 terminal->curr_attr.a |= ATTRMASK_BLINK;
1681                 break;
1682         case 8:
1683                 terminal->curr_attr.a |= ATTRMASK_CONCEALED;
1684                 break;
1685         case 2:
1686         case 21:
1687         case 22:
1688                 terminal->curr_attr.a &= ~ATTRMASK_BOLD;
1689                 if (terminal->curr_attr.fg < 16 && terminal->curr_attr.fg >= 8)
1690                         terminal->curr_attr.fg -= 8;
1691                 break;
1692         case 24:
1693                 terminal->curr_attr.a &= ~ATTRMASK_UNDERLINE;
1694                 break;
1695         case 25:
1696                 terminal->curr_attr.a &= ~ATTRMASK_BLINK;
1697                 break;
1698         case 7:
1699         case 26:
1700                 terminal->curr_attr.a |= ATTRMASK_INVERSE;
1701                 break;
1702         case 27:
1703                 terminal->curr_attr.a &= ~ATTRMASK_INVERSE;
1704                 break;
1705         case 28:
1706                 terminal->curr_attr.a &= ~ATTRMASK_CONCEALED;
1707                 break;
1708         case 39:
1709                 terminal->curr_attr.fg = terminal->color_scheme->default_attr.fg;
1710                 break;
1711         case 49:
1712                 terminal->curr_attr.bg = terminal->color_scheme->default_attr.bg;
1713                 break;
1714         default:
1715                 if(code >= 30 && code <= 37) {
1716                         terminal->curr_attr.fg = code - 30;
1717                         if (terminal->curr_attr.a & ATTRMASK_BOLD)
1718                                 terminal->curr_attr.fg += 8;
1719                 } else if(code >= 40 && code <= 47) {
1720                         terminal->curr_attr.bg = code - 40;
1721                 } else if (code >= 90 && code <= 97) {
1722                         terminal->curr_attr.fg = code - 90 + 8;
1723                 } else if (code >= 100 && code <= 107) {
1724                         terminal->curr_attr.bg = code - 100 + 8;
1725                 } else if(code >= 256 && code < 512) {
1726                         terminal->curr_attr.fg = code - 256;
1727                 } else if(code >= 512 && code < 768) {
1728                         terminal->curr_attr.bg = code - 512;
1729                 } else {
1730                         fprintf(stderr, "Unknown SGR code: %d\n", code);
1731                 }
1732                 break;
1733         }
1734 }
1735
1736 /* Returns 1 if c was special, otherwise 0 */
1737 static int
1738 handle_special_char(struct terminal *terminal, char c)
1739 {
1740         union utf8_char *row;
1741         struct attr *attr_row;
1742         
1743         row = terminal_get_row(terminal, terminal->row);
1744         attr_row = terminal_get_attr_row(terminal, terminal->row);
1745         
1746         switch(c) {
1747         case '\r':
1748                 terminal->column = 0;
1749                 break;
1750         case '\n':
1751                 if (terminal->mode & MODE_LF_NEWLINE) {
1752                         terminal->column = 0;
1753                 }
1754                 /* fallthrough */
1755         case '\v':
1756         case '\f':
1757                 terminal->row++;
1758                 if(terminal->row > terminal->margin_bottom) {
1759                         terminal->row = terminal->margin_bottom;
1760                         terminal_scroll(terminal, +1);
1761                 }
1762
1763                 break;
1764         case '\t':
1765                 while (terminal->column < terminal->width) {
1766                         if (terminal->tab_ruler[terminal->column]) break;
1767                         if (terminal->mode & MODE_IRM)
1768                                 terminal_shift_line(terminal, +1);
1769                         row[terminal->column].byte[0] = ' ';
1770                         row[terminal->column].byte[1] = '\0';
1771                         attr_row[terminal->column] = terminal->curr_attr;
1772                         terminal->column++;
1773                 }
1774                 if (terminal->column >= terminal->width) {
1775                         terminal->column = terminal->width - 1;
1776                 }
1777
1778                 break;
1779         case '\b':
1780                 if (terminal->column >= terminal->width) {
1781                         terminal->column = terminal->width - 2;
1782                 } else if (terminal->column > 0) {
1783                         terminal->column--;
1784                 } else if (terminal->mode & MODE_AUTOWRAP) {
1785                         terminal->column = terminal->width - 1;
1786                         terminal->row -= 1;
1787                         if (terminal->row < terminal->margin_top) {
1788                                 terminal->row = terminal->margin_top;
1789                                 terminal_scroll(terminal, -1);
1790                         }
1791                 }
1792
1793                 break;
1794         case '\a':
1795                 /* Bell */
1796                 break;
1797         case '\x0E': /* SO */
1798                 terminal->cs = terminal->g1;
1799                 break;
1800         case '\x0F': /* SI */
1801                 terminal->cs = terminal->g0;
1802                 break;
1803         default:
1804                 return 0;
1805         }
1806         
1807         return 1;
1808 }
1809
1810 static void
1811 handle_char(struct terminal *terminal, union utf8_char utf8)
1812 {
1813         union utf8_char *row;
1814         struct attr *attr_row;
1815         
1816         if (handle_special_char(terminal, utf8.byte[0])) return;
1817
1818         apply_char_set(terminal->cs, &utf8);
1819         
1820         /* There are a whole lot of non-characters, control codes,
1821          * and formatting codes that should probably be ignored,
1822          * for example: */
1823         if (strncmp((char*) utf8.byte, "\xEF\xBB\xBF", 3) == 0) {
1824                 /* BOM, ignore */
1825                 return;
1826         } 
1827         
1828         /* Some of these non-characters should be translated, e.g.: */
1829         if (utf8.byte[0] < 32) {
1830                 utf8.byte[0] = utf8.byte[0] + 64;
1831         }
1832         
1833         /* handle right margin effects */
1834         if (terminal->column >= terminal->width) {
1835                 if (terminal->mode & MODE_AUTOWRAP) {
1836                         terminal->column = 0;
1837                         terminal->row += 1;
1838                         if (terminal->row > terminal->margin_bottom) {
1839                                 terminal->row = terminal->margin_bottom;
1840                                 terminal_scroll(terminal, +1);
1841                         }
1842                 } else {
1843                         terminal->column--;
1844                 }
1845         }
1846         
1847         row = terminal_get_row(terminal, terminal->row);
1848         attr_row = terminal_get_attr_row(terminal, terminal->row);
1849         
1850         if (terminal->mode & MODE_IRM)
1851                 terminal_shift_line(terminal, +1);
1852         row[terminal->column] = utf8;
1853         attr_row[terminal->column++] = terminal->curr_attr;
1854
1855         if (utf8.ch != terminal->last_char.ch)
1856                 terminal->last_char = utf8;
1857 }
1858
1859 static void
1860 escape_append_utf8(struct terminal *terminal, union utf8_char utf8)
1861 {
1862         int len, i;
1863
1864         if ((utf8.byte[0] & 0x80) == 0x00)       len = 1;
1865         else if ((utf8.byte[0] & 0xE0) == 0xC0)  len = 2;
1866         else if ((utf8.byte[0] & 0xF0) == 0xE0)  len = 3;
1867         else if ((utf8.byte[0] & 0xF8) == 0xF0)  len = 4;
1868         else                                     len = 1;  /* Invalid, cannot happen */
1869
1870         if (terminal->escape_length + len <= MAX_ESCAPE) {
1871                 for (i = 0; i < len; i++)
1872                         terminal->escape[terminal->escape_length + i] = utf8.byte[i];
1873                 terminal->escape_length += len;
1874         } else if (terminal->escape_length < MAX_ESCAPE) {
1875                 terminal->escape[terminal->escape_length++] = 0;
1876         }
1877 }
1878
1879 static void
1880 terminal_data(struct terminal *terminal, const char *data, size_t length)
1881 {
1882         unsigned int i;
1883         union utf8_char utf8;
1884         enum utf8_state parser_state;
1885
1886         for (i = 0; i < length; i++) {
1887                 parser_state =
1888                         utf8_next_char(&terminal->state_machine, data[i]);
1889                 switch(parser_state) {
1890                 case utf8state_accept:
1891                         utf8.ch = terminal->state_machine.s.ch;
1892                         break;
1893                 case utf8state_reject:
1894                         /* the unicode replacement character */
1895                         utf8.byte[0] = 0xEF;
1896                         utf8.byte[1] = 0xBF;
1897                         utf8.byte[2] = 0xBD;
1898                         utf8.byte[3] = 0x00;
1899                         break;
1900                 default:
1901                         continue;
1902                 }
1903
1904                 /* assume escape codes never use non-ASCII characters */
1905                 switch (terminal->state) {
1906                 case escape_state_escape:
1907                         escape_append_utf8(terminal, utf8);
1908                         switch (utf8.byte[0]) {
1909                         case 'P':  /* DCS */
1910                                 terminal->state = escape_state_dcs;
1911                                 break;
1912                         case '[':  /* CSI */
1913                                 terminal->state = escape_state_csi;
1914                                 break;
1915                         case ']':  /* OSC */
1916                                 terminal->state = escape_state_osc;
1917                                 break;
1918                         case '#':
1919                         case '(':
1920                         case ')':  /* special */
1921                                 terminal->state = escape_state_special;
1922                                 break;
1923                         case '^':  /* PM (not implemented) */
1924                         case '_':  /* APC (not implemented) */
1925                                 terminal->state = escape_state_ignore;
1926                                 break;
1927                         default:
1928                                 terminal->state = escape_state_normal;
1929                                 handle_non_csi_escape(terminal, utf8.byte[0]);
1930                                 break;
1931                         }
1932                         continue;
1933                 case escape_state_csi:
1934                         if (handle_special_char(terminal, utf8.byte[0]) != 0) {
1935                                 /* do nothing */
1936                         } else if (utf8.byte[0] == '?') {
1937                                 terminal->escape_flags |= ESC_FLAG_WHAT;
1938                         } else if (utf8.byte[0] == '>') {
1939                                 terminal->escape_flags |= ESC_FLAG_GT;
1940                         } else if (utf8.byte[0] == '!') {
1941                                 terminal->escape_flags |= ESC_FLAG_BANG;
1942                         } else if (utf8.byte[0] == '$') {
1943                                 terminal->escape_flags |= ESC_FLAG_CASH;
1944                         } else if (utf8.byte[0] == '\'') {
1945                                 terminal->escape_flags |= ESC_FLAG_SQUOTE;
1946                         } else if (utf8.byte[0] == '"') {
1947                                 terminal->escape_flags |= ESC_FLAG_DQUOTE;
1948                         } else if (utf8.byte[0] == ' ') {
1949                                 terminal->escape_flags |= ESC_FLAG_SPACE;
1950                         } else {
1951                                 escape_append_utf8(terminal, utf8);
1952                                 if (terminal->escape_length >= MAX_ESCAPE)
1953                                         terminal->state = escape_state_normal;
1954                         }
1955                         
1956                         if (isalpha(utf8.byte[0]) || utf8.byte[0] == '@' ||
1957                                 utf8.byte[0] == '`')
1958                         {
1959                                 terminal->state = escape_state_normal;
1960                                 handle_escape(terminal);
1961                         } else {
1962                         }
1963                         continue;
1964                 case escape_state_inner_escape:
1965                         if (utf8.byte[0] == '\\') {
1966                                 terminal->state = escape_state_normal;
1967                                 if (terminal->outer_state == escape_state_dcs) {
1968                                         handle_dcs(terminal);
1969                                 } else if (terminal->outer_state == escape_state_osc) {
1970                                         handle_osc(terminal);
1971                                 }
1972                         } else if (utf8.byte[0] == '\e') {
1973                                 terminal->state = terminal->outer_state;
1974                                 escape_append_utf8(terminal, utf8);
1975                                 if (terminal->escape_length >= MAX_ESCAPE)
1976                                         terminal->state = escape_state_normal;
1977                         } else {
1978                                 terminal->state = terminal->outer_state;
1979                                 if (terminal->escape_length < MAX_ESCAPE)
1980                                         terminal->escape[terminal->escape_length++] = '\e';
1981                                 escape_append_utf8(terminal, utf8);
1982                                 if (terminal->escape_length >= MAX_ESCAPE)
1983                                         terminal->state = escape_state_normal;
1984                         }
1985                         continue;
1986                 case escape_state_dcs:
1987                 case escape_state_osc:
1988                 case escape_state_ignore:
1989                         if (utf8.byte[0] == '\e') {
1990                                 terminal->outer_state = terminal->state;
1991                                 terminal->state = escape_state_inner_escape;
1992                         } else if (utf8.byte[0] == '\a' && terminal->state == escape_state_osc) {
1993                                 terminal->state = escape_state_normal;
1994                                 handle_osc(terminal);
1995                         } else {
1996                                 escape_append_utf8(terminal, utf8);
1997                                 if (terminal->escape_length >= MAX_ESCAPE)
1998                                         terminal->state = escape_state_normal;
1999                         }
2000                         continue;
2001                 case escape_state_special:
2002                         escape_append_utf8(terminal, utf8);
2003                         terminal->state = escape_state_normal;
2004                         if (isdigit(utf8.byte[0]) || isalpha(utf8.byte[0])) {
2005                                 handle_special_escape(terminal, terminal->escape[1],
2006                                                       utf8.byte[0]);
2007                         }
2008                         continue;
2009                 default:
2010                         break;
2011                 }
2012
2013                 /* this is valid, because ASCII characters are never used to
2014                  * introduce a multibyte sequence in UTF-8 */
2015                 if (utf8.byte[0] == '\e') {
2016                         terminal->state = escape_state_escape;
2017                         terminal->outer_state = escape_state_normal;
2018                         terminal->escape[0] = '\e';
2019                         terminal->escape_length = 1;
2020                         terminal->escape_flags = 0;
2021                 } else {
2022                         handle_char(terminal, utf8);
2023                 } /* if */
2024         } /* for */
2025
2026         window_schedule_redraw(terminal->window);
2027 }
2028
2029 static void
2030 data_source_target(void *data,
2031                    struct wl_data_source *source, const char *mime_type)
2032 {
2033         fprintf(stderr, "data_source_target, %s\n", mime_type);
2034 }
2035
2036 static void
2037 data_source_send(void *data,
2038                  struct wl_data_source *source,
2039                  const char *mime_type, int32_t fd)
2040 {
2041         struct terminal *terminal = data;
2042
2043         terminal_send_selection(terminal, fd);
2044 }
2045
2046 static void
2047 data_source_cancelled(void *data, struct wl_data_source *source)
2048 {
2049         wl_data_source_destroy(source);
2050 }
2051
2052 static const struct wl_data_source_listener data_source_listener = {
2053         data_source_target,
2054         data_source_send,
2055         data_source_cancelled
2056 };
2057
2058 static int
2059 handle_bound_key(struct terminal *terminal,
2060                  struct input *input, uint32_t sym, uint32_t time)
2061 {
2062         switch (sym) {
2063         case XKB_KEY_X:
2064                 /* Cut selection; terminal doesn't do cut, fall
2065                  * through to copy. */
2066         case XKB_KEY_C:
2067                 terminal->selection =
2068                         display_create_data_source(terminal->display);
2069                 wl_data_source_offer(terminal->selection,
2070                                      "text/plain;charset=utf-8");
2071                 wl_data_source_add_listener(terminal->selection,
2072                                             &data_source_listener, terminal);
2073                 input_set_selection(input, terminal->selection,
2074                                     display_get_serial(terminal->display));
2075                 return 1;
2076         case XKB_KEY_V:
2077                 input_receive_selection_data_to_fd(input,
2078                                                    "text/plain;charset=utf-8",
2079                                                    terminal->master);
2080
2081                 return 1;
2082         default:
2083                 return 0;
2084         }
2085 }
2086
2087 static void
2088 key_handler(struct window *window, struct input *input, uint32_t time,
2089             uint32_t key, uint32_t sym, enum wl_keyboard_key_state state,
2090             void *data)
2091 {
2092         struct terminal *terminal = data;
2093         char ch[MAX_RESPONSE];
2094         uint32_t modifiers;
2095         int len = 0;
2096
2097         modifiers = input_get_modifiers(input);
2098         if ((modifiers & MOD_CONTROL_MASK) &&
2099             (modifiers & MOD_SHIFT_MASK) &&
2100             state == WL_KEYBOARD_KEY_STATE_PRESSED &&
2101             handle_bound_key(terminal, input, sym, time))
2102                 return;
2103
2104         switch (sym) {
2105         case XKB_KEY_F11:
2106                 if (state == WL_KEYBOARD_KEY_STATE_RELEASED)
2107                         break;
2108                 terminal->fullscreen ^= 1;
2109                 window_set_fullscreen(window, terminal->fullscreen);
2110                 break;
2111
2112         case XKB_KEY_BackSpace:
2113         case XKB_KEY_Tab:
2114         case XKB_KEY_Linefeed:
2115         case XKB_KEY_Clear:
2116         case XKB_KEY_Pause:
2117         case XKB_KEY_Scroll_Lock:
2118         case XKB_KEY_Sys_Req:
2119         case XKB_KEY_Escape:
2120                 ch[len++] = sym & 0x7f;
2121                 break;
2122
2123         case XKB_KEY_Return:
2124                 if (terminal->mode & MODE_LF_NEWLINE) {
2125                         ch[len++] = 0x0D;
2126                         ch[len++] = 0x0A;
2127                 } else {
2128                         ch[len++] = 0x0D;
2129                 }
2130                 break;
2131
2132         case XKB_KEY_Shift_L:
2133         case XKB_KEY_Shift_R:
2134         case XKB_KEY_Control_L:
2135         case XKB_KEY_Control_R:
2136         case XKB_KEY_Alt_L:
2137         case XKB_KEY_Alt_R:
2138                 break;
2139
2140         case XKB_KEY_Insert:
2141                 len = function_key_response('[', 2, modifiers, '~', ch);
2142                 break;
2143         case XKB_KEY_Delete:
2144                 if (terminal->mode & MODE_DELETE_SENDS_DEL) {
2145                         ch[len++] = '\x04';
2146                 } else {
2147                         len = function_key_response('[', 3, modifiers, '~', ch);
2148                 }
2149                 break;
2150         case XKB_KEY_Page_Up:
2151                 len = function_key_response('[', 5, modifiers, '~', ch);
2152                 break;
2153         case XKB_KEY_Page_Down:
2154                 len = function_key_response('[', 6, modifiers, '~', ch);
2155                 break;
2156         case XKB_KEY_F1:
2157                 len = function_key_response('O', 1, modifiers, 'P', ch);
2158                 break;
2159         case XKB_KEY_F2:
2160                 len = function_key_response('O', 1, modifiers, 'Q', ch);
2161                 break;
2162         case XKB_KEY_F3:
2163                 len = function_key_response('O', 1, modifiers, 'R', ch);
2164                 break;
2165         case XKB_KEY_F4:
2166                 len = function_key_response('O', 1, modifiers, 'S', ch);
2167                 break;
2168         case XKB_KEY_F5:
2169                 len = function_key_response('[', 15, modifiers, '~', ch);
2170                 break;
2171         case XKB_KEY_F6:
2172                 len = function_key_response('[', 17, modifiers, '~', ch);
2173                 break;
2174         case XKB_KEY_F7:
2175                 len = function_key_response('[', 18, modifiers, '~', ch);
2176                 break;
2177         case XKB_KEY_F8:
2178                 len = function_key_response('[', 19, modifiers, '~', ch);
2179                 break;
2180         case XKB_KEY_F9:
2181                 len = function_key_response('[', 20, modifiers, '~', ch);
2182                 break;
2183         case XKB_KEY_F10:
2184                 len = function_key_response('[', 21, modifiers, '~', ch);
2185                 break;
2186         case XKB_KEY_F12:
2187                 len = function_key_response('[', 24, modifiers, '~', ch);
2188                 break;
2189         default:
2190                 /* Handle special keys with alternate mappings */
2191                 len = apply_key_map(terminal->key_mode, sym, modifiers, ch);
2192                 if (len != 0) break;
2193                 
2194                 if (modifiers & MOD_CONTROL_MASK) {
2195                         if (sym >= '3' && sym <= '7')
2196                                 sym = (sym & 0x1f) + 8;
2197
2198                         if (!((sym >= '!' && sym <= '/') ||
2199                                 (sym >= '8' && sym <= '?') ||
2200                                 (sym >= '0' && sym <= '2'))) sym = sym & 0x1f;
2201                         else if (sym == '2') sym = 0x00;
2202                         else if (sym == '/') sym = 0x1F;
2203                         else if (sym == '8' || sym == '?') sym = 0x7F;
2204                 } else if ((terminal->mode & MODE_ALT_SENDS_ESC) && 
2205                            (modifiers & MOD_ALT_MASK))
2206                 {
2207                         ch[len++] = 0x1b;
2208                 } else if (modifiers & MOD_ALT_MASK) {
2209                         sym = sym | 0x80;
2210                 }
2211
2212                 if (sym < 256)
2213                         ch[len++] = sym;
2214                 break;
2215         }
2216
2217         if (state == WL_KEYBOARD_KEY_STATE_PRESSED && len > 0)
2218                 terminal_write(terminal, ch, len);
2219 }
2220
2221 static void
2222 keyboard_focus_handler(struct window *window,
2223                        struct input *device, void *data)
2224 {
2225         struct terminal *terminal = data;
2226
2227         terminal->focused = (device != NULL);
2228         window_schedule_redraw(terminal->window);
2229 }
2230
2231 static void
2232 button_handler(struct widget *widget,
2233                struct input *input, uint32_t time,
2234                uint32_t button,
2235                enum wl_pointer_button_state state, void *data)
2236 {
2237         struct terminal *terminal = data;
2238
2239         switch (button) {
2240         case 272:
2241                 if (state == WL_POINTER_BUTTON_STATE_PRESSED) {
2242                         terminal->dragging = 1;
2243                         input_get_position(input,
2244                                            &terminal->selection_start_x,
2245                                            &terminal->selection_start_y);
2246                         terminal->selection_end_x = terminal->selection_start_x;
2247                         terminal->selection_end_y = terminal->selection_start_y;
2248                         widget_schedule_redraw(widget);
2249                 } else {
2250                         terminal->dragging = 0;
2251                 }
2252                 break;
2253         }
2254 }
2255
2256 static int
2257 motion_handler(struct widget *widget,
2258                struct input *input, uint32_t time,
2259                float x, float y, void *data)
2260 {
2261         struct terminal *terminal = data;
2262
2263         if (terminal->dragging) {
2264                 input_get_position(input,
2265                                    &terminal->selection_end_x,
2266                                    &terminal->selection_end_y);
2267                 widget_schedule_redraw(widget);
2268         }
2269
2270         return CURSOR_IBEAM;
2271 }
2272
2273 static struct terminal *
2274 terminal_create(struct display *display, int fullscreen)
2275 {
2276         struct terminal *terminal;
2277         cairo_surface_t *surface;
2278         cairo_t *cr;
2279
2280         terminal = malloc(sizeof *terminal);
2281         if (terminal == NULL)
2282                 return terminal;
2283
2284         memset(terminal, 0, sizeof *terminal);
2285         terminal->fullscreen = fullscreen;
2286         terminal->color_scheme = &DEFAULT_COLORS;
2287         terminal_init(terminal);
2288         terminal->margin_top = 0;
2289         terminal->margin_bottom = -1;
2290         terminal->window = window_create(display);
2291         terminal->widget = frame_create(terminal->window, terminal);
2292         window_set_title(terminal->window, "Wayland Terminal");
2293         widget_set_transparent(terminal->widget, 0);
2294
2295         init_state_machine(&terminal->state_machine);
2296         init_color_table(terminal);
2297
2298         terminal->display = display;
2299         terminal->margin = 5;
2300
2301         window_set_user_data(terminal->window, terminal);
2302         window_set_key_handler(terminal->window, key_handler);
2303         window_set_keyboard_focus_handler(terminal->window,
2304                                           keyboard_focus_handler);
2305         widget_set_redraw_handler(terminal->widget, redraw_handler);
2306         widget_set_resize_handler(terminal->widget, resize_handler);
2307         widget_set_button_handler(terminal->widget, button_handler);
2308         widget_set_motion_handler(terminal->widget, motion_handler);
2309
2310         surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
2311         cr = cairo_create(surface);
2312         cairo_set_font_size(cr, 14);
2313         cairo_select_font_face (cr, "mono",
2314                                 CAIRO_FONT_SLANT_NORMAL,
2315                                 CAIRO_FONT_WEIGHT_BOLD);
2316         terminal->font_bold = cairo_get_scaled_font (cr);
2317         cairo_scaled_font_reference(terminal->font_bold);
2318
2319         cairo_select_font_face (cr, "mono",
2320                                 CAIRO_FONT_SLANT_NORMAL,
2321                                 CAIRO_FONT_WEIGHT_NORMAL);
2322         terminal->font_normal = cairo_get_scaled_font (cr);
2323         cairo_scaled_font_reference(terminal->font_normal);
2324
2325         cairo_font_extents(cr, &terminal->extents);
2326         cairo_destroy(cr);
2327         cairo_surface_destroy(surface);
2328
2329         window_schedule_resize(terminal->window, 500, 400);
2330
2331         return terminal;
2332 }
2333
2334 static void
2335 io_handler(struct task *task, uint32_t events)
2336 {
2337         struct terminal *terminal =
2338                 container_of(task, struct terminal, io_task);
2339         char buffer[256];
2340         int len;
2341
2342         if (events & EPOLLHUP)
2343                 exit(0);
2344
2345         len = read(terminal->master, buffer, sizeof buffer);
2346         if (len < 0)
2347                 exit(0);
2348
2349         terminal_data(terminal, buffer, len);
2350 }
2351
2352 static int
2353 terminal_run(struct terminal *terminal, const char *path)
2354 {
2355         int master;
2356         pid_t pid;
2357
2358         pid = forkpty(&master, NULL, NULL, NULL);
2359         if (pid == 0) {
2360                 setenv("TERM", "xterm-256color", 1);
2361                 setenv("COLORTERM", "xterm-256color", 1);
2362                 if (execl(path, path, NULL)) {
2363                         printf("exec failed: %m\n");
2364                         exit(EXIT_FAILURE);
2365                 }
2366         } else if (pid < 0) {
2367                 fprintf(stderr, "failed to fork and create pty (%m).\n");
2368                 return -1;
2369         }
2370
2371         terminal->master = master;
2372         fcntl(master, F_SETFL, O_NONBLOCK);
2373         terminal->io_task.run = io_handler;
2374         display_watch_fd(terminal->display, terminal->master,
2375                          EPOLLIN | EPOLLHUP, &terminal->io_task);
2376
2377         window_set_fullscreen(terminal->window, terminal->fullscreen);
2378         if (!terminal->fullscreen)
2379                 terminal_resize(terminal, 80, 24);
2380
2381         return 0;
2382 }
2383
2384 static const struct weston_option terminal_options[] = {
2385         { WESTON_OPTION_BOOLEAN, "fullscreen", 'f', &option_fullscreen },
2386 };
2387
2388 int main(int argc, char *argv[])
2389 {
2390         struct display *d;
2391         struct terminal *terminal;
2392         const char *shell;
2393
2394         argc = parse_options(terminal_options,
2395                              ARRAY_LENGTH(terminal_options), argc, argv);
2396
2397         d = display_create(argc, argv);
2398         if (d == NULL) {
2399                 fprintf(stderr, "failed to create display: %m\n");
2400                 return -1;
2401         }
2402
2403         shell = getenv("SHELL");
2404         if (!shell)
2405                 shell = "/bin/bash";
2406
2407         terminal = terminal_create(d, option_fullscreen);
2408         if (terminal_run(terminal, shell))
2409                 exit(EXIT_FAILURE);
2410
2411         display_run(d);
2412
2413         return 0;
2414 }