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