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