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