Use cairo_push_group() for double buffering in the terminal
[profile/ivi/weston.git] / clients / terminal.c
1 /*
2  * Copyright © 2008 Kristian Høgsberg
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that copyright
7  * notice and this permission notice appear in supporting documentation, and
8  * that the name of the copyright holders not be used in advertising or
9  * publicity pertaining to distribution of the software without specific,
10  * written prior permission.  The copyright holders make no representations
11  * about the suitability of this software for any purpose.  It is provided "as
12  * is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
20  * OF THIS SOFTWARE.
21  */
22
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <math.h>
30 #include <time.h>
31 #include <pty.h>
32 #include <ctype.h>
33 #include <cairo.h>
34 #include <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         surface = window_get_surface(terminal->window);
898         window_get_child_allocation(terminal->window, &allocation);
899         cr = cairo_create(surface);
900         cairo_rectangle(cr, allocation.x, allocation.y,
901                         allocation.width, allocation.height);
902         cairo_clip(cr);
903         cairo_push_group(cr);
904
905         cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
906         terminal_set_color(terminal, cr, terminal->color_scheme->border);
907         cairo_paint(cr);
908
909         cairo_set_scaled_font(cr, terminal->font_normal);
910
911         extents = terminal->extents;
912         side_margin = (allocation.width - terminal->width * extents.max_x_advance) / 2;
913         top_margin = (allocation.height - terminal->height * extents.height) / 2;
914
915         cairo_set_line_width(cr, 1.0);
916         cairo_translate(cr, allocation.x + side_margin,
917                         allocation.y + top_margin);
918         /* paint the background */
919         for (row = 0; row < terminal->height; row++) {
920                 for (col = 0; col < terminal->width; col++) {
921                         /* get the attributes for this character cell */
922                         terminal_decode_attr(terminal, row, col, &attr);
923
924                         if (attr.attr.bg == terminal->color_scheme->border)
925                                 continue;
926
927                         terminal_set_color(terminal, cr, attr.attr.bg);
928                         cairo_move_to(cr, col * extents.max_x_advance,
929                                       row * extents.height);
930                         cairo_rel_line_to(cr, extents.max_x_advance, 0);
931                         cairo_rel_line_to(cr, 0, extents.height);
932                         cairo_rel_line_to(cr, -extents.max_x_advance, 0);
933                         cairo_close_path(cr);
934                         cairo_fill(cr);
935                 }
936         }
937
938         cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
939
940         /* paint the foreground */
941         glyph_run_init(&run, terminal, cr);
942         for (row = 0; row < terminal->height; row++) {
943                 p_row = terminal_get_row(terminal, row);
944                 for (col = 0; col < terminal->width; col++) {
945                         /* get the attributes for this character cell */
946                         terminal_decode_attr(terminal, row, col, &attr);
947
948                         glyph_run_flush(&run, attr);
949
950                         text_x = col * extents.max_x_advance;
951                         text_y = extents.ascent + row * extents.height;
952                         if (attr.attr.a & ATTRMASK_UNDERLINE) {
953                                 terminal_set_color(terminal, cr, attr.attr.fg);
954                                 cairo_move_to(cr, text_x, (double)text_y + 1.5);
955                                 cairo_line_to(cr, text_x + extents.max_x_advance, (double) text_y + 1.5);
956                                 cairo_stroke(cr);
957                         }
958
959                         glyph_run_add(&run, text_x, text_y, &p_row[col]);
960                 }
961         }
962
963         attr.key = ~0;
964         glyph_run_flush(&run, attr);
965
966         if ((terminal->mode & MODE_SHOW_CURSOR) && !terminal->focused) {
967                 d = 0.5;
968
969                 cairo_set_line_width(cr, 1);
970                 cairo_move_to(cr, terminal->column * extents.max_x_advance + d,
971                               terminal->row * extents.height + d);
972                 cairo_rel_line_to(cr, extents.max_x_advance - 2 * d, 0);
973                 cairo_rel_line_to(cr, 0, extents.height - 2 * d);
974                 cairo_rel_line_to(cr, -extents.max_x_advance + 2 * d, 0);
975                 cairo_close_path(cr);
976
977                 cairo_stroke(cr);
978         }
979
980         cairo_pop_group_to_source(cr);
981         cairo_paint(cr);
982         cairo_destroy(cr);
983         cairo_surface_destroy(surface);
984 }
985
986 static void
987 resize_handler(struct window *window,
988                int32_t pixel_width, int32_t pixel_height, void *data)
989 {
990         struct terminal *terminal = data;
991         int32_t width, height;
992
993         width = (pixel_width - 2 * terminal->margin) /
994                 (int32_t) terminal->extents.max_x_advance;
995         height = (pixel_height - 2 * terminal->margin) /
996                 (int32_t) terminal->extents.height;
997
998         terminal_resize(terminal, width, height);
999 }
1000
1001 static void
1002 terminal_draw(struct terminal *terminal)
1003 {
1004         window_draw(terminal->window);
1005         terminal_draw_contents(terminal);
1006         window_flush(terminal->window);
1007 }
1008
1009 static void
1010 redraw_handler(struct window *window, void *data)
1011 {
1012         struct terminal *terminal = data;
1013
1014         terminal_draw(terminal);
1015 }
1016
1017 static void
1018 terminal_data(struct terminal *terminal, const char *data, size_t length);
1019
1020 static void
1021 handle_char(struct terminal *terminal, union utf8_char utf8);
1022
1023 static void
1024 handle_sgr(struct terminal *terminal, int code);
1025
1026 static void
1027 handle_term_parameter(struct terminal *terminal, int code, int sr)
1028 {
1029         int i;
1030
1031         if (terminal->escape_flags & ESC_FLAG_WHAT) {
1032                 switch(code) {
1033                 case 1:  /* DECCKM */
1034                         if (sr) terminal->key_mode = KM_APPLICATION;
1035                         else    terminal->key_mode = KM_NORMAL;
1036                         break;
1037                 case 2:  /* DECANM */
1038                         /* No VT52 support yet */
1039                         terminal->g0 = CS_US;
1040                         terminal->g1 = CS_US;
1041                         terminal->cs = terminal->g0;
1042                         break;
1043                 case 3:  /* DECCOLM */
1044                         if (sr)
1045                                 terminal_resize(terminal, 132, 24);
1046                         else
1047                                 terminal_resize(terminal, 80, 24);
1048                         
1049                         /* set columns, but also home cursor and clear screen */
1050                         terminal->row = 0; terminal->column = 0;
1051                         for (i = 0; i < terminal->height; i++) {
1052                                 memset(terminal_get_row(terminal, i),
1053                                     0, terminal->data_pitch);
1054                                 attr_init(terminal_get_attr_row(terminal, i),
1055                                     terminal->curr_attr, terminal->width);
1056                         }
1057                         break;
1058                 case 5:  /* DECSCNM */
1059                         if (sr) terminal->mode |=  MODE_INVERSE;
1060                         else    terminal->mode &= ~MODE_INVERSE;
1061                         break;
1062                 case 6:  /* DECOM */
1063                         terminal->origin_mode = sr;
1064                         if (terminal->origin_mode)
1065                                 terminal->row = terminal->margin_top;
1066                         else
1067                                 terminal->row = 0;
1068                         terminal->column = 0;
1069                         break;
1070                 case 7:  /* DECAWM */
1071                         if (sr) terminal->mode |=  MODE_AUTOWRAP;
1072                         else    terminal->mode &= ~MODE_AUTOWRAP;
1073                         break;
1074                 case 8:  /* DECARM */
1075                         if (sr) terminal->mode |=  MODE_AUTOREPEAT;
1076                         else    terminal->mode &= ~MODE_AUTOREPEAT;
1077                         break;
1078                 case 25:
1079                         if (sr) terminal->mode |=  MODE_SHOW_CURSOR;
1080                         else    terminal->mode &= ~MODE_SHOW_CURSOR;
1081                         break;
1082                 case 1037:   /* deleteSendsDel */
1083                         if (sr) terminal->mode |=  MODE_DELETE_SENDS_DEL;
1084                         else    terminal->mode &= ~MODE_DELETE_SENDS_DEL;
1085                         break;
1086                 case 1039:   /* altSendsEscape */
1087                         if (sr) terminal->mode |=  MODE_ALT_SENDS_ESC;
1088                         else    terminal->mode &= ~MODE_ALT_SENDS_ESC;
1089                         break;
1090                 default:
1091                         fprintf(stderr, "Unknown parameter: ?%d\n", code);
1092                         break;
1093                 }
1094         } else {
1095                 switch(code) {
1096                 case 4:  /* IRM */
1097                         if (sr) terminal->mode |=  MODE_IRM;
1098                         else    terminal->mode &= ~MODE_IRM;
1099                         break;
1100                 case 20: /* LNM */
1101                         if (sr) terminal->mode |=  MODE_LF_NEWLINE;
1102                         else    terminal->mode &= ~MODE_LF_NEWLINE;
1103                         break;
1104                 default:
1105                         fprintf(stderr, "Unknown parameter: %d\n", code);
1106                         break;
1107                 }
1108         }
1109 }
1110
1111 static void
1112 handle_dcs(struct terminal *terminal)
1113 {
1114 }
1115
1116 static void
1117 handle_osc(struct terminal *terminal)
1118 {
1119 }
1120
1121 static void
1122 handle_escape(struct terminal *terminal)
1123 {
1124         union utf8_char *row;
1125         struct attr *attr_row;
1126         char *p;
1127         int i, count, x, y, top, bottom;
1128         int args[10], set[10] = { 0, };
1129         char response[MAX_RESPONSE] = {0, };
1130
1131         terminal->escape[terminal->escape_length++] = '\0';
1132         i = 0;
1133         p = &terminal->escape[2];
1134         while ((isdigit(*p) || *p == ';') && i < 10) {
1135                 if (*p == ';') {
1136                         if (!set[i]) {
1137                                 args[i] = 0;
1138                                 set[i] = 1;
1139                         }
1140                         p++;
1141                         i++;
1142                 } else {
1143                         args[i] = strtol(p, &p, 10);
1144                         set[i] = 1;
1145                 }
1146         }
1147         
1148         switch (*p) {
1149         case '@':    /* ICH */
1150                 count = set[0] ? args[0] : 1;
1151                 if (count == 0) count = 1;
1152                 terminal_shift_line(terminal, count);
1153                 break;
1154         case 'A':    /* CUU */
1155                 count = set[0] ? args[0] : 1;
1156                 if (count == 0) count = 1;
1157                 if (terminal->row - count >= terminal->margin_top)
1158                         terminal->row -= count;
1159                 else
1160                         terminal->row = terminal->margin_top;
1161                 break;
1162         case 'B':    /* CUD */
1163                 count = set[0] ? args[0] : 1;
1164                 if (count == 0) count = 1;
1165                 if (terminal->row + count <= terminal->margin_bottom)
1166                         terminal->row += count;
1167                 else
1168                         terminal->row = terminal->margin_bottom;
1169                 break;
1170         case 'C':    /* CUF */
1171                 count = set[0] ? args[0] : 1;
1172                 if (count == 0) count = 1;
1173                 if ((terminal->column + count) < terminal->width)
1174                         terminal->column += count;
1175                 else
1176                         terminal->column = terminal->width - 1;
1177                 break;
1178         case 'D':    /* CUB */
1179                 count = set[0] ? args[0] : 1;
1180                 if (count == 0) count = 1;
1181                 if ((terminal->column - count) >= 0)
1182                         terminal->column -= count;
1183                 else
1184                         terminal->column = 0;
1185                 break;
1186         case 'E':    /* CNL */
1187                 count = set[0] ? args[0] : 1;
1188                 if (terminal->row + count <= terminal->margin_bottom)
1189                         terminal->row += count;
1190                 else
1191                         terminal->row = terminal->margin_bottom;
1192                 terminal->column = 0;
1193                 break;
1194         case 'F':    /* CPL */
1195                 count = set[0] ? args[0] : 1;
1196                 if (terminal->row - count >= terminal->margin_top)
1197                         terminal->row -= count;
1198                 else
1199                         terminal->row = terminal->margin_top;
1200                 terminal->column = 0;
1201                 break;
1202         case 'G':    /* CHA */
1203                 y = set[0] ? args[0] : 1;
1204                 y = y <= 0 ? 1 : y > terminal->width ? terminal->width : y;
1205                 
1206                 terminal->column = y - 1;
1207                 break;
1208         case 'f':    /* HVP */
1209         case 'H':    /* CUP */
1210                 x = (set[1] ? args[1] : 1) - 1;
1211                 x = x < 0 ? 0 :
1212                     (x >= terminal->width ? terminal->width - 1 : x);
1213                 
1214                 y = (set[0] ? args[0] : 1) - 1;
1215                 if (terminal->origin_mode) {
1216                         y += terminal->margin_top;
1217                         y = y < terminal->margin_top ? terminal->margin_top :
1218                             (y > terminal->margin_bottom ? terminal->margin_bottom : y);
1219                 } else {
1220                         y = y < 0 ? 0 :
1221                             (y >= terminal->height ? terminal->height - 1 : y);
1222                 }
1223                 
1224                 terminal->row = y;
1225                 terminal->column = x;
1226                 break;
1227         case 'I':    /* CHT */
1228                 count = set[0] ? args[0] : 1;
1229                 if (count == 0) count = 1;
1230                 while (count > 0 && terminal->column < terminal->width) {
1231                         if (terminal->tab_ruler[terminal->column]) count--;
1232                         terminal->column++;
1233                 }
1234                 terminal->column--;
1235                 break;
1236         case 'J':    /* ED */
1237                 row = terminal_get_row(terminal, terminal->row);
1238                 attr_row = terminal_get_attr_row(terminal, terminal->row);
1239                 if (!set[0] || args[0] == 0 || args[0] > 2) {
1240                         memset(&row[terminal->column],
1241                                0, (terminal->width - terminal->column) * sizeof(union utf8_char));
1242                         attr_init(&attr_row[terminal->column],
1243                                terminal->curr_attr, terminal->width - terminal->column);
1244                         for (i = terminal->row + 1; i < terminal->height; i++) {
1245                                 memset(terminal_get_row(terminal, i),
1246                                     0, terminal->data_pitch);
1247                                 attr_init(terminal_get_attr_row(terminal, i),
1248                                     terminal->curr_attr, terminal->width);
1249                         }
1250                 } else if (args[0] == 1) {
1251                         memset(row, 0, (terminal->column+1) * sizeof(union utf8_char));
1252                         attr_init(attr_row, terminal->curr_attr, terminal->column+1);
1253                         for (i = 0; i < terminal->row; i++) {
1254                                 memset(terminal_get_row(terminal, i),
1255                                     0, terminal->data_pitch);
1256                                 attr_init(terminal_get_attr_row(terminal, i),
1257                                     terminal->curr_attr, terminal->width);
1258                         }
1259                 } else if (args[0] == 2) {
1260                         for (i = 0; i < terminal->height; i++) {
1261                                 memset(terminal_get_row(terminal, i),
1262                                     0, terminal->data_pitch);
1263                                 attr_init(terminal_get_attr_row(terminal, i),
1264                                     terminal->curr_attr, terminal->width);
1265                         }
1266                 }
1267                 break;
1268         case 'K':    /* EL */
1269                 row = terminal_get_row(terminal, terminal->row);
1270                 attr_row = terminal_get_attr_row(terminal, terminal->row);
1271                 if (!set[0] || args[0] == 0 || args[0] > 2) {
1272                         memset(&row[terminal->column], 0,
1273                             (terminal->width - terminal->column) * sizeof(union utf8_char));
1274                         attr_init(&attr_row[terminal->column], terminal->curr_attr,
1275                             terminal->width - terminal->column);
1276                 } else if (args[0] == 1) {
1277                         memset(row, 0, (terminal->column+1) * sizeof(union utf8_char));
1278                         attr_init(attr_row, terminal->curr_attr, terminal->column+1);
1279                 } else if (args[0] == 2) {
1280                         memset(row, 0, terminal->data_pitch);
1281                         attr_init(attr_row, terminal->curr_attr, terminal->width);
1282                 }
1283                 break;
1284         case 'L':    /* IL */
1285                 count = set[0] ? args[0] : 1;
1286                 if (count == 0) count = 1;
1287                 if (terminal->row >= terminal->margin_top &&
1288                         terminal->row < terminal->margin_bottom)
1289                 {
1290                         top = terminal->margin_top;
1291                         terminal->margin_top = terminal->row;
1292                         terminal_scroll(terminal, 0 - count);
1293                         terminal->margin_top = top;
1294                 } else if (terminal->row == terminal->margin_bottom) {
1295                         memset(terminal_get_row(terminal, terminal->row),
1296                                0, terminal->data_pitch);
1297                         attr_init(terminal_get_attr_row(terminal, terminal->row),
1298                                 terminal->curr_attr, terminal->width);
1299                 }
1300                 break;
1301         case 'M':    /* DL */
1302                 count = set[0] ? args[0] : 1;
1303                 if (count == 0) count = 1;
1304                 if (terminal->row >= terminal->margin_top &&
1305                         terminal->row < terminal->margin_bottom)
1306                 {
1307                         top = terminal->margin_top;
1308                         terminal->margin_top = terminal->row;
1309                         terminal_scroll(terminal, count);
1310                         terminal->margin_top = top;
1311                 } else if (terminal->row == terminal->margin_bottom) {
1312                         memset(terminal_get_row(terminal, terminal->row),
1313                                0, terminal->data_pitch);
1314                 }
1315                 break;
1316         case 'P':    /* DCH */
1317                 count = set[0] ? args[0] : 1;
1318                 if (count == 0) count = 1;
1319                 terminal_shift_line(terminal, 0 - count);
1320                 break;
1321         case 'S':    /* SU */
1322                 terminal_scroll(terminal, set[0] ? args[0] : 1);
1323                 break;
1324         case 'T':    /* SD */
1325                 terminal_scroll(terminal, 0 - (set[0] ? args[0] : 1));
1326                 break;
1327         case 'X':    /* ECH */
1328                 count = set[0] ? args[0] : 1;
1329                 if (count == 0) count = 1;
1330                 if ((terminal->column + count) > terminal->width)
1331                         count = terminal->width - terminal->column;
1332                 row = terminal_get_row(terminal, terminal->row);
1333                 attr_row = terminal_get_attr_row(terminal, terminal->row);
1334                 memset(&row[terminal->column], 0, count * sizeof(union utf8_char));
1335                 attr_init(&attr_row[terminal->column], terminal->curr_attr, count);
1336                 break;
1337         case 'Z':    /* CBT */
1338                 count = set[0] ? args[0] : 1;
1339                 if (count == 0) count = 1;
1340                 while (count > 0 && terminal->column >= 0) {
1341                         if (terminal->tab_ruler[terminal->column]) count--;
1342                         terminal->column--;
1343                 }
1344                 terminal->column++;
1345                 break;
1346         case '`':    /* HPA */
1347                 y = set[0] ? args[0] : 1;
1348                 y = y <= 0 ? 1 : y > terminal->width ? terminal->width : y;
1349                 
1350                 terminal->column = y - 1;
1351                 break;
1352         case 'b':    /* REP */
1353                 count = set[0] ? args[0] : 1;
1354                 if (count == 0) count = 1;
1355                 if (terminal->last_char.byte[0])
1356                         for (i = 0; i < count; i++)
1357                                 handle_char(terminal, terminal->last_char);
1358                 terminal->last_char.byte[0] = 0;
1359                 break;
1360         case 'c':    /* Primary DA */
1361                 write(terminal->master, "\e[?6c", 5);
1362                 break;
1363         case 'd':    /* VPA */
1364                 x = set[0] ? args[0] : 1;
1365                 x = x <= 0 ? 1 : x > terminal->height ? terminal->height : x;
1366                 
1367                 terminal->row = x - 1;
1368                 break;
1369         case 'g':    /* TBC */
1370                 if (!set[0] || args[0] == 0) {
1371                         terminal->tab_ruler[terminal->column] = 0;
1372                 } else if (args[0] == 3) {
1373                         memset(terminal->tab_ruler, 0, terminal->width);
1374                 }
1375                 break;
1376         case 'h':    /* SM */
1377                 for(i = 0; i < 10 && set[i]; i++) {
1378                         handle_term_parameter(terminal, args[i], 1);
1379                 }
1380                 break;
1381         case 'l':    /* RM */
1382                 for(i = 0; i < 10 && set[i]; i++) {
1383                         handle_term_parameter(terminal, args[i], 0);
1384                 }
1385                 break;
1386         case 'm':    /* SGR */
1387                 for(i = 0; i < 10; i++) {
1388                         if (i <= 7 && set[i] && set[i + 1] &&
1389                                 set[i + 2] && args[i + 1] == 5)
1390                         {
1391                                 if (args[i] == 38) {
1392                                         handle_sgr(terminal, args[i + 2] + 256);
1393                                         break;
1394                                 } else if (args[i] == 48) {
1395                                         handle_sgr(terminal, args[i + 2] + 512);
1396                                         break;
1397                                 }
1398                         }
1399                         if(set[i]) {
1400                                 handle_sgr(terminal, args[i]);
1401                         } else if(i == 0) {
1402                                 handle_sgr(terminal, 0);
1403                                 break;
1404                         } else {
1405                                 break;
1406                         }
1407                 }
1408                 break;
1409         case 'n':    /* DSR */
1410                 i = set[0] ? args[0] : 0;
1411                 if (i == 0 || i == 5) {
1412                         write(terminal->master, "\e[0n", 4);
1413                 } else if (i == 6) {
1414                         snprintf(response, MAX_RESPONSE, "\e[%d;%dR",
1415                                  terminal->origin_mode ?
1416                                      terminal->row+terminal->margin_top : terminal->row+1,
1417                                  terminal->column+1);
1418                         write(terminal->master, response, strlen(response));
1419                 }
1420                 break;
1421         case 'r':
1422                 if(!set[0]) {
1423                         terminal->margin_top = 0;
1424                         terminal->margin_bottom = terminal->height-1;
1425                         terminal->row = 0;
1426                         terminal->column = 0;
1427                 } else {
1428                         top = (set[0] ? args[0] : 1) - 1;
1429                         top = top < 0 ? 0 :
1430                               (top >= terminal->height ? terminal->height - 1 : top);
1431                         bottom = (set[1] ? args[1] : 1) - 1;
1432                         bottom = bottom < 0 ? 0 :
1433                                  (bottom >= terminal->height ? terminal->height - 1 : bottom);
1434                         if(bottom > top) {
1435                                 terminal->margin_top = top;
1436                                 terminal->margin_bottom = bottom;
1437                         } else {
1438                                 terminal->margin_top = 0;
1439                                 terminal->margin_bottom = terminal->height-1;
1440                         }
1441                         if(terminal->origin_mode)
1442                                 terminal->row = terminal->margin_top;
1443                         else
1444                                 terminal->row = 0;
1445                         terminal->column = 0;
1446                 }
1447                 break;
1448         case 's':
1449                 terminal->saved_row = terminal->row;
1450                 terminal->saved_column = terminal->column;
1451                 break;
1452         case 'u':
1453                 terminal->row = terminal->saved_row;
1454                 terminal->column = terminal->saved_column;
1455                 break;
1456         default:
1457                 fprintf(stderr, "Unknown CSI escape: %c\n", *p);
1458                 break;
1459         }       
1460 }
1461
1462 static void
1463 handle_non_csi_escape(struct terminal *terminal, char code)
1464 {
1465         switch(code) {
1466         case 'M':    /* RI */
1467                 terminal->row -= 1;
1468                 if(terminal->row < terminal->margin_top) {
1469                         terminal->row = terminal->margin_top;
1470                         terminal_scroll(terminal, -1);
1471                 }
1472                 break;
1473         case 'E':    /* NEL */
1474                 terminal->column = 0;
1475                 // fallthrough
1476         case 'D':    /* IND */
1477                 terminal->row += 1;
1478                 if(terminal->row > terminal->margin_bottom) {
1479                         terminal->row = terminal->margin_bottom;
1480                         terminal_scroll(terminal, +1);
1481                 }
1482                 break;
1483         case 'c':    /* RIS */
1484                 terminal_init(terminal);
1485                 break;
1486         case 'H':    /* HTS */
1487                 terminal->tab_ruler[terminal->column] = 1;
1488                 break;
1489         case '7':    /* DECSC */
1490                 terminal->saved_row = terminal->row;
1491                 terminal->saved_column = terminal->column;
1492                 terminal->saved_attr = terminal->curr_attr;
1493                 terminal->saved_origin_mode = terminal->origin_mode;
1494                 terminal->saved_cs = terminal->cs;
1495                 terminal->saved_g0 = terminal->g0;
1496                 terminal->saved_g1 = terminal->g1;
1497                 break;
1498         case '8':    /* DECRC */
1499                 terminal->row = terminal->saved_row;
1500                 terminal->column = terminal->saved_column;
1501                 terminal->curr_attr = terminal->saved_attr;
1502                 terminal->origin_mode = terminal->saved_origin_mode;
1503                 terminal->cs = terminal->saved_cs;
1504                 terminal->g0 = terminal->saved_g0;
1505                 terminal->g1 = terminal->saved_g1;
1506                 break;
1507         case '=':    /* DECPAM */
1508                 terminal->key_mode = KM_APPLICATION;
1509                 break;
1510         case '>':    /* DECPNM */
1511                 terminal->key_mode = KM_NORMAL;
1512                 break;
1513         default:
1514                 fprintf(stderr, "Unknown escape code: %c\n", code);
1515                 break;
1516         }
1517 }
1518
1519 static void
1520 handle_special_escape(struct terminal *terminal, char special, char code)
1521 {
1522         int i, numChars;
1523
1524         if (special == '#') {
1525                 switch(code) {
1526                 case '8':
1527                         /* fill with 'E', no cheap way to do this */
1528                         memset(terminal->data, 0, terminal->data_pitch * terminal->height);
1529                         numChars = terminal->width * terminal->height;
1530                         for(i = 0; i < numChars; i++) {
1531                                 terminal->data[i].byte[0] = 'E';
1532                         }
1533                         break;
1534                 default:
1535                         fprintf(stderr, "Unknown HASH escape #%c\n", code);
1536                         break;
1537                 }
1538         } else if (special == '(' || special == ')') {
1539                 switch(code) {
1540                 case '0':
1541                         if (special == '(')
1542                                 terminal->g0 = CS_SPECIAL;
1543                         else
1544                                 terminal->g1 = CS_SPECIAL;
1545                         break;
1546                 case 'A':
1547                         if (special == '(')
1548                                 terminal->g0 = CS_UK;
1549                         else
1550                                 terminal->g1 = CS_UK;
1551                         break;
1552                 case 'B':
1553                         if (special == '(')
1554                                 terminal->g0 = CS_US;
1555                         else
1556                                 terminal->g1 = CS_US;
1557                         break;
1558                 default:
1559                         fprintf(stderr, "Unknown character set %c\n", code);
1560                         break;
1561                 }
1562         } else {
1563                 fprintf(stderr, "Unknown special escape %c%c\n", special, code);
1564         }
1565 }
1566
1567 static void
1568 handle_sgr(struct terminal *terminal, int code)
1569 {
1570         switch(code) {
1571         case 0:
1572                 terminal->curr_attr = terminal->color_scheme->default_attr;
1573                 break;
1574         case 1:
1575                 terminal->curr_attr.a |= ATTRMASK_BOLD;
1576                 if (terminal->curr_attr.fg < 8)
1577                         terminal->curr_attr.fg += 8;
1578                 break;
1579         case 4:
1580                 terminal->curr_attr.a |= ATTRMASK_UNDERLINE;
1581                 break;
1582         case 5:
1583                 terminal->curr_attr.a |= ATTRMASK_BLINK;
1584                 break;
1585         case 8:
1586                 terminal->curr_attr.a |= ATTRMASK_CONCEALED;
1587                 break;
1588         case 2:
1589         case 21:
1590         case 22:
1591                 terminal->curr_attr.a &= ~ATTRMASK_BOLD;
1592                 if (terminal->curr_attr.fg < 16 && terminal->curr_attr.fg >= 8)
1593                         terminal->curr_attr.fg -= 8;
1594                 break;
1595         case 24:
1596                 terminal->curr_attr.a &= ~ATTRMASK_UNDERLINE;
1597                 break;
1598         case 25:
1599                 terminal->curr_attr.a &= ~ATTRMASK_BLINK;
1600                 break;
1601         case 7:
1602         case 26:
1603                 terminal->curr_attr.a |= ATTRMASK_INVERSE;
1604                 break;
1605         case 27:
1606                 terminal->curr_attr.a &= ~ATTRMASK_INVERSE;
1607                 break;
1608         case 28:
1609                 terminal->curr_attr.a &= ~ATTRMASK_CONCEALED;
1610                 break;
1611         case 39:
1612                 terminal->curr_attr.fg = terminal->color_scheme->default_attr.fg;
1613                 break;
1614         case 49:
1615                 terminal->curr_attr.bg = terminal->color_scheme->default_attr.bg;
1616                 break;
1617         default:
1618                 if(code >= 30 && code <= 37) {
1619                         terminal->curr_attr.fg = code - 30;
1620                         if (terminal->curr_attr.a & ATTRMASK_BOLD)
1621                                 terminal->curr_attr.fg += 8;
1622                 } else if(code >= 40 && code <= 47) {
1623                         terminal->curr_attr.bg = code - 40;
1624                 } else if (code >= 90 && code <= 97) {
1625                         terminal->curr_attr.fg = code - 90 + 8;
1626                 } else if (code >= 100 && code <= 107) {
1627                         terminal->curr_attr.bg = code - 100 + 8;
1628                 } else if(code >= 256 && code < 512) {
1629                         terminal->curr_attr.fg = code - 256;
1630                 } else if(code >= 512 && code < 768) {
1631                         terminal->curr_attr.bg = code - 512;
1632                 } else {
1633                         fprintf(stderr, "Unknown SGR code: %d\n", code);
1634                 }
1635                 break;
1636         }
1637 }
1638
1639 /* Returns 1 if c was special, otherwise 0 */
1640 static int
1641 handle_special_char(struct terminal *terminal, char c)
1642 {
1643         union utf8_char *row;
1644         struct attr *attr_row;
1645         
1646         row = terminal_get_row(terminal, terminal->row);
1647         attr_row = terminal_get_attr_row(terminal, terminal->row);
1648         
1649         switch(c) {
1650         case '\r':
1651                 terminal->column = 0;
1652                 break;
1653         case '\n':
1654                 if (terminal->mode & MODE_LF_NEWLINE) {
1655                         terminal->column = 0;
1656                 }
1657                 /* fallthrough */
1658         case '\v':
1659         case '\f':
1660                 terminal->row++;
1661                 if(terminal->row > terminal->margin_bottom) {
1662                         terminal->row = terminal->margin_bottom;
1663                         terminal_scroll(terminal, +1);
1664                 }
1665
1666                 break;
1667         case '\t':
1668                 while (terminal->column < terminal->width) {
1669                         if (terminal->tab_ruler[terminal->column]) break;
1670                         if (terminal->mode & MODE_IRM)
1671                                 terminal_shift_line(terminal, +1);
1672                         row[terminal->column].byte[0] = ' ';
1673                         row[terminal->column].byte[1] = '\0';
1674                         attr_row[terminal->column] = terminal->curr_attr;
1675                         terminal->column++;
1676                 }
1677                 if (terminal->column >= terminal->width) {
1678                         terminal->column = terminal->width - 1;
1679                 }
1680
1681                 break;
1682         case '\b':
1683                 if (terminal->column >= terminal->width) {
1684                         terminal->column = terminal->width - 2;
1685                 } else if (terminal->column > 0) {
1686                         terminal->column--;
1687                 } else if (terminal->mode & MODE_AUTOWRAP) {
1688                         terminal->column = terminal->width - 1;
1689                         terminal->row -= 1;
1690                         if (terminal->row < terminal->margin_top) {
1691                                 terminal->row = terminal->margin_top;
1692                                 terminal_scroll(terminal, -1);
1693                         }
1694                 }
1695
1696                 break;
1697         case '\a':
1698                 /* Bell */
1699                 break;
1700         case '\x0E': /* SO */
1701                 terminal->cs = terminal->g1;
1702                 break;
1703         case '\x0F': /* SI */
1704                 terminal->cs = terminal->g0;
1705                 break;
1706         default:
1707                 return 0;
1708         }
1709         
1710         return 1;
1711 }
1712
1713 static void
1714 handle_char(struct terminal *terminal, union utf8_char utf8)
1715 {
1716         union utf8_char *row;
1717         struct attr *attr_row;
1718         
1719         if (handle_special_char(terminal, utf8.byte[0])) return;
1720
1721         apply_char_set(terminal->cs, &utf8);
1722         
1723         /* There are a whole lot of non-characters, control codes,
1724          * and formatting codes that should probably be ignored,
1725          * for example: */
1726         if (strncmp((char*) utf8.byte, "\xEF\xBB\xBF", 3) == 0) {
1727                 /* BOM, ignore */
1728                 return;
1729         } 
1730         
1731         /* Some of these non-characters should be translated, e.g.: */
1732         if (utf8.byte[0] < 32) {
1733                 utf8.byte[0] = utf8.byte[0] + 64;
1734         }
1735         
1736         /* handle right margin effects */
1737         if (terminal->column >= terminal->width) {
1738                 if (terminal->mode & MODE_AUTOWRAP) {
1739                         terminal->column = 0;
1740                         terminal->row += 1;
1741                         if (terminal->row > terminal->margin_bottom) {
1742                                 terminal->row = terminal->margin_bottom;
1743                                 terminal_scroll(terminal, +1);
1744                         }
1745                 } else {
1746                         terminal->column--;
1747                 }
1748         }
1749         
1750         row = terminal_get_row(terminal, terminal->row);
1751         attr_row = terminal_get_attr_row(terminal, terminal->row);
1752         
1753         if (terminal->mode & MODE_IRM)
1754                 terminal_shift_line(terminal, +1);
1755         row[terminal->column] = utf8;
1756         attr_row[terminal->column++] = terminal->curr_attr;
1757
1758         if (utf8.ch != terminal->last_char.ch)
1759                 terminal->last_char = utf8;
1760 }
1761
1762 static void
1763 escape_append_utf8(struct terminal *terminal, union utf8_char utf8)
1764 {
1765         int len, i;
1766
1767         if ((utf8.byte[0] & 0x80) == 0x00)       len = 1;
1768         else if ((utf8.byte[0] & 0xE0) == 0xC0)  len = 2;
1769         else if ((utf8.byte[0] & 0xF0) == 0xE0)  len = 3;
1770         else if ((utf8.byte[0] & 0xF8) == 0xF0)  len = 4;
1771         else                                     len = 1;  /* Invalid, cannot happen */
1772
1773         if (terminal->escape_length + len <= MAX_ESCAPE) {
1774                 for (i = 0; i < len; i++)
1775                         terminal->escape[terminal->escape_length + i] = utf8.byte[i];
1776                 terminal->escape_length += len;
1777         } else if (terminal->escape_length < MAX_ESCAPE) {
1778                 terminal->escape[terminal->escape_length++] = 0;
1779         }
1780 }
1781
1782 static void
1783 terminal_data(struct terminal *terminal, const char *data, size_t length)
1784 {
1785         int i;
1786         union utf8_char utf8;
1787         enum utf8_state parser_state;
1788
1789         for (i = 0; i < length; i++) {
1790                 parser_state =
1791                         utf8_next_char(&terminal->state_machine, data[i]);
1792                 switch(parser_state) {
1793                 case utf8state_accept:
1794                         utf8.ch = terminal->state_machine.s.ch;
1795                         break;
1796                 case utf8state_reject:
1797                         /* the unicode replacement character */
1798                         utf8.byte[0] = 0xEF;
1799                         utf8.byte[1] = 0xBF;
1800                         utf8.byte[2] = 0xBD;
1801                         utf8.byte[3] = 0x00;
1802                         break;
1803                 default:
1804                         continue;
1805                 }
1806
1807                 /* assume escape codes never use non-ASCII characters */
1808                 switch (terminal->state) {
1809                 case escape_state_escape:
1810                         escape_append_utf8(terminal, utf8);
1811                         switch (utf8.byte[0]) {
1812                         case 'P':  /* DCS */
1813                                 terminal->state = escape_state_dcs;
1814                                 break;
1815                         case '[':  /* CSI */
1816                                 terminal->state = escape_state_csi;
1817                                 break;
1818                         case ']':  /* OSC */
1819                                 terminal->state = escape_state_osc;
1820                                 break;
1821                         case '#':
1822                         case '(':
1823                         case ')':  /* special */
1824                                 terminal->state = escape_state_special;
1825                                 break;
1826                         case '^':  /* PM (not implemented) */
1827                         case '_':  /* APC (not implemented) */
1828                                 terminal->state = escape_state_ignore;
1829                                 break;
1830                         default:
1831                                 terminal->state = escape_state_normal;
1832                                 handle_non_csi_escape(terminal, utf8.byte[0]);
1833                                 break;
1834                         }
1835                         continue;
1836                 case escape_state_csi:
1837                         if (handle_special_char(terminal, utf8.byte[0]) != 0) {
1838                                 /* do nothing */
1839                         } else if (utf8.byte[0] == '?') {
1840                                 terminal->escape_flags |= ESC_FLAG_WHAT;
1841                         } else if (utf8.byte[0] == '>') {
1842                                 terminal->escape_flags |= ESC_FLAG_GT;
1843                         } else if (utf8.byte[0] == '!') {
1844                                 terminal->escape_flags |= ESC_FLAG_BANG;
1845                         } else if (utf8.byte[0] == '$') {
1846                                 terminal->escape_flags |= ESC_FLAG_CASH;
1847                         } else if (utf8.byte[0] == '\'') {
1848                                 terminal->escape_flags |= ESC_FLAG_SQUOTE;
1849                         } else if (utf8.byte[0] == '"') {
1850                                 terminal->escape_flags |= ESC_FLAG_DQUOTE;
1851                         } else if (utf8.byte[0] == ' ') {
1852                                 terminal->escape_flags |= ESC_FLAG_SPACE;
1853                         } else {
1854                                 escape_append_utf8(terminal, utf8);
1855                                 if (terminal->escape_length >= MAX_ESCAPE)
1856                                         terminal->state = escape_state_normal;
1857                         }
1858                         
1859                         if (isalpha(utf8.byte[0]) || utf8.byte[0] == '@' ||
1860                                 utf8.byte[0] == '`')
1861                         {
1862                                 terminal->state = escape_state_normal;
1863                                 handle_escape(terminal);
1864                         } else {
1865                         }
1866                         continue;
1867                 case escape_state_inner_escape:
1868                         if (utf8.byte[0] == '\\') {
1869                                 terminal->state = escape_state_normal;
1870                                 if (terminal->outer_state == escape_state_dcs) {
1871                                         handle_dcs(terminal);
1872                                 } else if (terminal->outer_state == escape_state_osc) {
1873                                         handle_osc(terminal);
1874                                 }
1875                         } else if (utf8.byte[0] == '\e') {
1876                                 terminal->state = terminal->outer_state;
1877                                 escape_append_utf8(terminal, utf8);
1878                                 if (terminal->escape_length >= MAX_ESCAPE)
1879                                         terminal->state = escape_state_normal;
1880                         } else {
1881                                 terminal->state = terminal->outer_state;
1882                                 if (terminal->escape_length < MAX_ESCAPE)
1883                                         terminal->escape[terminal->escape_length++] = '\e';
1884                                 escape_append_utf8(terminal, utf8);
1885                                 if (terminal->escape_length >= MAX_ESCAPE)
1886                                         terminal->state = escape_state_normal;
1887                         }
1888                         continue;
1889                 case escape_state_dcs:
1890                 case escape_state_osc:
1891                 case escape_state_ignore:
1892                         if (utf8.byte[0] == '\e') {
1893                                 terminal->outer_state = terminal->state;
1894                                 terminal->state = escape_state_inner_escape;
1895                         } else if (utf8.byte[0] == '\a' && terminal->state == escape_state_osc) {
1896                                 terminal->state = escape_state_normal;
1897                                 handle_osc(terminal);
1898                         } else {
1899                                 escape_append_utf8(terminal, utf8);
1900                                 if (terminal->escape_length >= MAX_ESCAPE)
1901                                         terminal->state = escape_state_normal;
1902                         }
1903                         continue;
1904                 case escape_state_special:
1905                         escape_append_utf8(terminal, utf8);
1906                         terminal->state = escape_state_normal;
1907                         if (isdigit(utf8.byte[0]) || isalpha(utf8.byte[0])) {
1908                                 handle_special_escape(terminal, terminal->escape[1],
1909                                                       utf8.byte[0]);
1910                         }
1911                         continue;
1912                 default:
1913                         break;
1914                 }
1915
1916                 /* this is valid, because ASCII characters are never used to
1917                  * introduce a multibyte sequence in UTF-8 */
1918                 if (utf8.byte[0] == '\e') {
1919                         terminal->state = escape_state_escape;
1920                         terminal->outer_state = escape_state_normal;
1921                         terminal->escape[0] = '\e';
1922                         terminal->escape_length = 1;
1923                         terminal->escape_flags = 0;
1924                 } else {
1925                         handle_char(terminal, utf8);
1926                 } /* if */
1927         } /* for */
1928
1929         window_schedule_redraw(terminal->window);
1930 }
1931
1932 static void
1933 selection_listener_send(void *data, struct wl_selection *selection,
1934                         const char *mime_type, int fd)
1935 {
1936         static const char msg[] = "selection data";
1937
1938         fprintf(stderr, "selection send, fd is %d\n", fd);
1939         write(fd, msg, sizeof msg - 1);
1940         close(fd);
1941 }
1942
1943 static void
1944 selection_listener_cancelled(void *data, struct wl_selection *selection)
1945 {
1946         fprintf(stderr, "selection cancelled\n");
1947         wl_selection_destroy(selection);
1948 }
1949
1950 static const struct wl_selection_listener selection_listener = {
1951         selection_listener_send,
1952         selection_listener_cancelled
1953 };
1954
1955 static gboolean
1956 selection_io_func(GIOChannel *source, GIOCondition condition, gpointer data)
1957 {
1958         struct terminal *terminal = data;
1959         char buffer[256];
1960         unsigned int len;
1961         int fd;
1962
1963         fd = g_io_channel_unix_get_fd(source);
1964         len = read(fd, buffer, sizeof buffer);
1965         fprintf(stderr, "read %d bytes: %.*s\n", len, len, buffer);
1966
1967         write(terminal->master, buffer, len);
1968
1969         close(fd);
1970         g_source_remove(terminal->tag);
1971
1972         g_io_channel_unref(source);
1973
1974         return TRUE;
1975 }
1976
1977 static int
1978 handle_bound_key(struct terminal *terminal,
1979                  struct input *input, uint32_t sym, uint32_t time)
1980 {
1981         struct wl_shell *shell;
1982         GIOChannel *channel;
1983         int fd;
1984
1985         switch (sym) {
1986         case XK_C:
1987                 shell = display_get_shell(terminal->display);
1988                 terminal->selection = wl_shell_create_selection(shell);
1989                 wl_selection_add_listener(terminal->selection,
1990                                           &selection_listener, terminal);
1991                 wl_selection_offer(terminal->selection, "text/plain");
1992                 wl_selection_activate(terminal->selection,
1993                                       input_get_input_device(input), time);
1994
1995                 return 1;
1996         case XK_V:
1997                 if (input_offers_mime_type(input, "text/plain")) {
1998                         fd = input_receive_mime_type(input, "text/plain");
1999                         channel = g_io_channel_unix_new(fd);
2000                         terminal->tag = g_io_add_watch(channel, G_IO_IN,
2001                                                        selection_io_func,
2002                                                        terminal);
2003                 }
2004
2005                 return 1;
2006         case XK_X:
2007                 /* cut selection; terminal doesn't do cut */
2008                 return 0;
2009         default:
2010                 return 0;
2011         }
2012 }
2013
2014 static void
2015 key_handler(struct window *window, struct input *input, uint32_t time,
2016             uint32_t key, uint32_t sym, uint32_t state, void *data)
2017 {
2018         struct terminal *terminal = data;
2019         char ch[MAX_RESPONSE];
2020         uint32_t modifiers;
2021         int len = 0;
2022
2023         modifiers = input_get_modifiers(input);
2024         if ((modifiers & XKB_COMMON_CONTROL_MASK) &&
2025             (modifiers & XKB_COMMON_SHIFT_MASK) &&
2026             state && handle_bound_key(terminal, input, sym, 0))
2027                 return;
2028
2029         switch (sym) {
2030         case XK_F11:
2031                 if (!state)
2032                         break;
2033                 terminal->fullscreen ^= 1;
2034                 window_set_fullscreen(window, terminal->fullscreen);
2035                 window_schedule_redraw(terminal->window);
2036                 break;
2037
2038         case XK_BackSpace:
2039         case XK_Tab:
2040         case XK_Linefeed:
2041         case XK_Clear:
2042         case XK_Pause:
2043         case XK_Scroll_Lock:
2044         case XK_Sys_Req:
2045         case XK_Escape:
2046                 ch[len++] = sym & 0x7f;
2047                 break;
2048
2049         case XK_Return:
2050                 if (terminal->mode & MODE_LF_NEWLINE) {
2051                         ch[len++] = 0x0D;
2052                         ch[len++] = 0x0A;
2053                 } else {
2054                         ch[len++] = 0x0D;
2055                 }
2056                 break;
2057
2058         case XK_Shift_L:
2059         case XK_Shift_R:
2060         case XK_Control_L:
2061         case XK_Control_R:
2062         case XK_Alt_L:
2063         case XK_Alt_R:
2064                 break;
2065
2066         case XK_Insert:
2067                 len = function_key_response('[', 2, modifiers, '~', ch);
2068                 break;
2069         case XK_Delete:
2070                 if (terminal->mode & MODE_DELETE_SENDS_DEL) {
2071                         ch[len++] = '\x04';
2072                 } else {
2073                         len = function_key_response('[', 3, modifiers, '~', ch);
2074                 }
2075                 break;
2076         case XK_Page_Up:
2077                 len = function_key_response('[', 5, modifiers, '~', ch);
2078                 break;
2079         case XK_Page_Down:
2080                 len = function_key_response('[', 6, modifiers, '~', ch);
2081                 break;
2082         case XK_F1:
2083                 len = function_key_response('O', 1, modifiers, 'P', ch);
2084                 break;
2085         case XK_F2:
2086                 len = function_key_response('O', 1, modifiers, 'Q', ch);
2087                 break;
2088         case XK_F3:
2089                 len = function_key_response('O', 1, modifiers, 'R', ch);
2090                 break;
2091         case XK_F4:
2092                 len = function_key_response('O', 1, modifiers, 'S', ch);
2093                 break;
2094         case XK_F5:
2095                 len = function_key_response('[', 15, modifiers, '~', ch);
2096                 break;
2097         case XK_F6:
2098                 len = function_key_response('[', 17, modifiers, '~', ch);
2099                 break;
2100         case XK_F7:
2101                 len = function_key_response('[', 18, modifiers, '~', ch);
2102                 break;
2103         case XK_F8:
2104                 len = function_key_response('[', 19, modifiers, '~', ch);
2105                 break;
2106         case XK_F9:
2107                 len = function_key_response('[', 20, modifiers, '~', ch);
2108                 break;
2109         case XK_F10:
2110                 len = function_key_response('[', 21, modifiers, '~', ch);
2111                 break;
2112         case XK_F12:
2113                 len = function_key_response('[', 24, modifiers, '~', ch);
2114                 break;
2115         default:
2116                 /* Handle special keys with alternate mappings */
2117                 len = apply_key_map(terminal->key_mode, sym, modifiers, ch);
2118                 if (len != 0) break;
2119                 
2120                 if (modifiers & XKB_COMMON_CONTROL_MASK) {
2121                         if (sym >= '3' && sym <= '7')
2122                                 sym = (sym & 0x1f) + 8;
2123
2124                         if (!((sym >= '!' && sym <= '/') ||
2125                                 (sym >= '8' && sym <= '?') ||
2126                                 (sym >= '0' && sym <= '2'))) sym = sym & 0x1f;
2127                         else if (sym == '2') sym = 0x00;
2128                         else if (sym == '/') sym = 0x1F;
2129                         else if (sym == '8' || sym == '?') sym = 0x7F;
2130                 } else if ((terminal->mode & MODE_ALT_SENDS_ESC) && 
2131                            (modifiers & XKB_COMMON_MOD1_MASK))
2132                 {
2133                         ch[len++] = 0x1b;
2134                 } else if (modifiers & XKB_COMMON_MOD1_MASK) {
2135                         sym = sym | 0x80;
2136                 }
2137
2138                 if (sym < 256)
2139                         ch[len++] = sym;
2140                 break;
2141         }
2142
2143         if (state && len > 0)
2144                 write(terminal->master, ch, len);
2145 }
2146
2147 static void
2148 keyboard_focus_handler(struct window *window,
2149                        struct input *device, void *data)
2150 {
2151         struct terminal *terminal = data;
2152
2153         terminal->focused = (device != NULL);
2154         window_schedule_redraw(terminal->window);
2155 }
2156
2157 static void
2158 button_handler(struct window *window,
2159                struct input *input, uint32_t time,
2160                int button, int state, void *data)
2161 {
2162         struct terminal *terminal = data;
2163
2164         switch (button) {
2165         case 272:
2166                 if (state) {
2167                         terminal->dragging = 1;
2168                         terminal->selection_active = 0;
2169                         input_get_position(input,
2170                                            &terminal->selection_start_x,
2171                                            &terminal->selection_start_y);
2172                         terminal->selection_end_x = terminal->selection_start_x;
2173                         terminal->selection_end_y = terminal->selection_start_y;
2174                         window_schedule_redraw(window);
2175                 } else {
2176                         terminal->dragging = 0;
2177                 }
2178                 break;
2179         }
2180 }
2181
2182 static int
2183 motion_handler(struct window *window,
2184                struct input *input, uint32_t time,
2185                int32_t x, int32_t y,
2186                int32_t sx, int32_t sy, void *data)
2187 {
2188         struct terminal *terminal = data;
2189
2190         if (terminal->dragging) {
2191                 terminal->selection_active = 1;
2192                 input_get_position(input,
2193                                    &terminal->selection_end_x,
2194                                    &terminal->selection_end_y);
2195                 window_schedule_redraw(window);
2196         }
2197
2198         return POINTER_IBEAM;
2199 }
2200
2201 static struct terminal *
2202 terminal_create(struct display *display, int fullscreen)
2203 {
2204         struct terminal *terminal;
2205         cairo_surface_t *surface;
2206         cairo_t *cr;
2207
2208         terminal = malloc(sizeof *terminal);
2209         if (terminal == NULL)
2210                 return terminal;
2211
2212         memset(terminal, 0, sizeof *terminal);
2213         terminal->fullscreen = fullscreen;
2214         terminal->color_scheme = &DEFAULT_COLORS;
2215         terminal_init(terminal);
2216         terminal->margin_top = 0;
2217         terminal->margin_bottom = -1;
2218         terminal->window = window_create(display, "Wayland Terminal",
2219                                          500, 400);
2220
2221         init_state_machine(&terminal->state_machine);
2222         init_color_table(terminal);
2223
2224         terminal->display = display;
2225         terminal->margin = 5;
2226
2227         window_set_fullscreen(terminal->window, terminal->fullscreen);
2228         window_set_user_data(terminal->window, terminal);
2229         window_set_redraw_handler(terminal->window, redraw_handler);
2230         window_set_resize_handler(terminal->window, resize_handler);
2231
2232         window_set_key_handler(terminal->window, key_handler);
2233         window_set_keyboard_focus_handler(terminal->window,
2234                                           keyboard_focus_handler);
2235         window_set_button_handler(terminal->window, button_handler);
2236         window_set_motion_handler(terminal->window, motion_handler);
2237
2238         surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
2239         cr = cairo_create(surface);
2240         cairo_set_font_size(cr, 14);
2241         cairo_select_font_face (cr, "mono",
2242                                 CAIRO_FONT_SLANT_NORMAL,
2243                                 CAIRO_FONT_WEIGHT_BOLD);
2244         terminal->font_bold = cairo_get_scaled_font (cr);
2245         cairo_scaled_font_reference(terminal->font_bold);
2246
2247         cairo_select_font_face (cr, "mono",
2248                                 CAIRO_FONT_SLANT_NORMAL,
2249                                 CAIRO_FONT_WEIGHT_NORMAL);
2250         terminal->font_normal = cairo_get_scaled_font (cr);
2251         cairo_scaled_font_reference(terminal->font_normal);
2252
2253         cairo_font_extents(cr, &terminal->extents);
2254         cairo_destroy(cr);
2255         cairo_surface_destroy(surface);
2256
2257         terminal_resize(terminal, 80, 24);
2258         terminal_draw(terminal);
2259
2260         return terminal;
2261 }
2262
2263 static gboolean
2264 io_handler(GIOChannel   *source,
2265            GIOCondition  condition,
2266            gpointer      data)
2267 {
2268         struct terminal *terminal = data;
2269         gchar buffer[256];
2270         gsize bytes_read;
2271         GError *error = NULL;
2272
2273         g_io_channel_read_chars(source, buffer, sizeof buffer,
2274                                 &bytes_read, &error);
2275
2276         terminal_data(terminal, buffer, bytes_read);
2277
2278         return TRUE;
2279 }
2280
2281 static int
2282 terminal_run(struct terminal *terminal, const char *path)
2283 {
2284         int master;
2285         pid_t pid;
2286
2287         pid = forkpty(&master, NULL, NULL, NULL);
2288         if (pid == 0) {
2289                 setenv("TERM", "xterm-256color", 1);
2290                 setenv("COLORTERM", "xterm-256color", 1);
2291                 if (execl(path, path, NULL)) {
2292                         printf("exec failed: %m\n");
2293                         exit(EXIT_FAILURE);
2294                 }
2295         } else if (pid < 0) {
2296                 fprintf(stderr, "failed to fork and create pty (%m).\n");
2297                 return -1;
2298         }
2299
2300         terminal->master = master;
2301         terminal->channel = g_io_channel_unix_new(master);
2302         fcntl(master, F_SETFL, O_NONBLOCK);
2303         g_io_add_watch(terminal->channel, G_IO_IN,
2304                        io_handler, terminal);
2305
2306         return 0;
2307 }
2308
2309 static const GOptionEntry option_entries[] = {
2310         { "fullscreen", 'f', 0, G_OPTION_ARG_NONE,
2311           &option_fullscreen, "Run in fullscreen mode" },
2312         { NULL }
2313 };
2314
2315 int main(int argc, char *argv[])
2316 {
2317         struct display *d;
2318         struct terminal *terminal;
2319
2320         d = display_create(&argc, &argv, option_entries);
2321         if (d == NULL) {
2322                 fprintf(stderr, "failed to create display: %m\n");
2323                 return -1;
2324         }
2325
2326         terminal = terminal_create(d, option_fullscreen);
2327         if (terminal_run(terminal, "/bin/bash"))
2328                 exit(EXIT_FAILURE);
2329
2330         display_run(d);
2331
2332         return 0;
2333 }