terminal: Fancy colors
[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
55 union utf8_char {
56         unsigned char byte[4];
57         uint32_t ch;
58 };
59
60 enum utf8_state {
61         utf8state_start,
62         utf8state_accept,
63         utf8state_reject,
64         utf8state_expect3,
65         utf8state_expect2,
66         utf8state_expect1
67 };
68
69 struct utf8_state_machine {
70         enum utf8_state state;
71         int len;
72         union utf8_char s;
73 };
74
75 static void
76 init_state_machine(struct utf8_state_machine *machine)
77 {
78         machine->state = utf8state_start;
79         machine->len = 0;
80         machine->s.ch = 0;
81 }
82
83 static enum utf8_state
84 utf8_next_char(struct utf8_state_machine *machine, char c)
85 {
86         switch(machine->state) {
87         case utf8state_start:
88         case utf8state_accept:
89         case utf8state_reject:
90                 machine->s.ch = 0;
91                 machine->len = 0;
92                 if(c == 0xC0 || c == 0xC1) {
93                         /* overlong encoding, reject */
94                         machine->state = utf8state_reject;
95                 } else if((c & 0x80) == 0) {
96                         /* single byte, accept */
97                         machine->s.byte[machine->len++] = c;
98                         machine->state = utf8state_accept;
99                 } else if((c & 0xC0) == 0x80) {
100                         /* parser out of sync, ignore byte */
101                         machine->state = utf8state_start;
102                 } else if((c & 0xE0) == 0xC0) {
103                         /* start of two byte sequence */
104                         machine->s.byte[machine->len++] = c;
105                         machine->state = utf8state_expect1;
106                 } else if((c & 0xF0) == 0xE0) {
107                         /* start of three byte sequence */
108                         machine->s.byte[machine->len++] = c;
109                         machine->state = utf8state_expect2;
110                 } else if((c & 0xF8) == 0xF0) {
111                         /* start of four byte sequence */
112                         machine->s.byte[machine->len++] = c;
113                         machine->state = utf8state_expect3;
114                 } else {
115                         /* overlong encoding, reject */
116                         machine->state = utf8state_reject;
117                 }
118                 break;
119         case utf8state_expect3:
120                 machine->s.byte[machine->len++] = c;
121                 if((c & 0xC0) == 0x80) {
122                         /* all good, continue */
123                         machine->state = utf8state_expect2;
124                 } else {
125                         /* missing extra byte, reject */
126                         machine->state = utf8state_reject;
127                 }
128                 break;
129         case utf8state_expect2:
130                 machine->s.byte[machine->len++] = c;
131                 if((c & 0xC0) == 0x80) {
132                         /* all good, continue */
133                         machine->state = utf8state_expect1;
134                 } else {
135                         /* missing extra byte, reject */
136                         machine->state = utf8state_reject;
137                 }
138                 break;
139         case utf8state_expect1:
140                 machine->s.byte[machine->len++] = c;
141                 if((c & 0xC0) == 0x80) {
142                         /* all good, accept */
143                         machine->state = utf8state_accept;
144                 } else {
145                         /* missing extra byte, reject */
146                         machine->state = utf8state_reject;
147                 }
148                 break;
149         default:
150                 machine->state = utf8state_reject;
151                 break;
152         }
153         
154         return machine->state;
155 }
156
157 struct terminal_color { double r, g, b, a; };
158 struct attr {
159         unsigned char fg, bg;
160         char a;        /* attributes format:
161                         * 76543210
162                         *     ilub */
163         char r;        /* reserved */
164 };
165 struct color_scheme {
166         struct terminal_color palette[16];
167         struct terminal_color border;
168         struct attr default_attr;
169 };
170
171 static void
172 attr_init(struct attr *data_attr, struct attr attr, int n)
173 {
174         int i;
175         for (i = 0; i < n; i++) {
176                 data_attr[i] = attr;
177         }
178 }
179
180 struct terminal {
181         struct window *window;
182         struct display *display;
183         union utf8_char *data;
184         struct attr *data_attr;
185         struct attr curr_attr;
186         union utf8_char last_char;
187         int data_pitch, attr_pitch;  /* The width in bytes of a line */
188         int width, height, start, row, column;
189         int fd, master;
190         GIOChannel *channel;
191         uint32_t modifiers;
192         char escape[64];
193         int escape_length;
194         int state;
195         struct utf8_state_machine state_machine;
196         int margin;
197         int fullscreen;
198         int focused;
199         struct color_scheme *color_scheme;
200         struct terminal_color color_table[256];
201         cairo_font_extents_t extents;
202         cairo_font_face_t *font_normal, *font_bold;
203 };
204
205 static void
206 terminal_init(struct terminal *terminal)
207 {
208         terminal->curr_attr = terminal->color_scheme->default_attr;
209
210         terminal->row = 0;
211         terminal->column = 0;
212 }
213
214 static void
215 init_color_table(struct terminal *terminal)
216 {
217         int c, r;
218         struct terminal_color *color_table = terminal->color_table;
219
220         for (c = 0; c < 256; c ++) {
221                 if (c < 16) {
222                         color_table[c] = terminal->color_scheme->palette[c];
223                 } else if (c < 232) {
224                         r = c - 16;
225                         color_table[c].b = ((double)(r % 6) / 6.0); r /= 6;
226                         color_table[c].g = ((double)(r % 6) / 6.0); r /= 6;
227                         color_table[c].r = ((double)(r % 6) / 6.0);
228                         color_table[c].a = 1.0;
229                 } else {
230                         r = (c - 232) * 10 + 8;
231                         color_table[c].r = ((double) r) / 256.0;
232                         color_table[c].g = color_table[c].r;
233                         color_table[c].b = color_table[c].r;
234                         color_table[c].a = 1.0;
235                 }
236         }
237 }
238
239 static union utf8_char *
240 terminal_get_row(struct terminal *terminal, int row)
241 {
242         int index;
243
244         index = (row + terminal->start) % terminal->height;
245
246         return &terminal->data[index * terminal->width];
247 }
248
249 static struct attr*
250 terminal_get_attr_row(struct terminal *terminal, int row) {
251         int index;
252
253         index = (row + terminal->start) % terminal->height;
254
255         return &terminal->data_attr[index * terminal->width];
256 }
257
258 static struct attr
259 terminal_get_attr(struct terminal *terminal, int row, int col) {
260         return terminal_get_attr_row(terminal, row)[col];
261 }
262
263 static void
264 terminal_resize(struct terminal *terminal, int width, int height)
265 {
266         size_t size;
267         union utf8_char *data;
268         struct attr *data_attr;
269         int data_pitch, attr_pitch;
270         int i, l, total_rows, start;
271
272         if (terminal->width == width && terminal->height == height)
273                 return;
274
275         data_pitch = width * sizeof(union utf8_char);
276         size = data_pitch * height;
277         data = malloc(size);
278         attr_pitch = width * sizeof(struct attr);
279         data_attr = malloc(attr_pitch * height);
280         memset(data, 0, size);
281         attr_init(data_attr, terminal->curr_attr, width * height);
282         if (terminal->data && terminal->data_attr) {
283                 if (width > terminal->width)
284                         l = terminal->width;
285                 else
286                         l = width;
287
288                 if (terminal->height > height) {
289                         total_rows = height;
290                         start = terminal->height - height;
291                 } else {
292                         total_rows = terminal->height;
293                         start = 0;
294                 }
295
296                 for (i = 0; i < total_rows; i++) {
297                         memcpy(&data[width * i],
298                                terminal_get_row(terminal, i),
299                                l * sizeof(union utf8_char));
300                         memcpy(&data_attr[width * i],
301                                terminal_get_attr_row(terminal, i),
302                                l * sizeof(struct attr));
303                 }
304
305                 free(terminal->data);
306                 free(terminal->data_attr);
307         }
308
309         terminal->data_pitch = data_pitch;
310         terminal->attr_pitch = attr_pitch;
311         terminal->width = width;
312         terminal->height = height;
313         terminal->data = data;
314         terminal->data_attr = data_attr;
315
316         if (terminal->row >= terminal->height)
317                 terminal->row = terminal->height - 1;
318         if (terminal->column >= terminal->width)
319                 terminal->column = terminal->width - 1;
320         terminal->start = 0;
321 }
322
323 struct color_scheme DEFAULT_COLORS = {
324         {
325                 {0,    0,    0,    1}, /* black */
326                 {0.66, 0,    0,    1}, /* red */
327                 {0  ,  0.66, 0,    1}, /* green */
328                 {0.66, 0.33, 0,    1}, /* orange (nicer than muddy yellow) */
329                 {0  ,  0  ,  0.66, 1}, /* blue */
330                 {0.66, 0  ,  0.66, 1}, /* magenta */
331                 {0,    0.66, 0.66, 1}, /* cyan */
332                 {0.66, 0.66, 0.66, 1}, /* light grey */
333                 {0.22, 0.33, 0.33, 1}, /* dark grey */
334                 {1,    0.33, 0.33, 1}, /* high red */
335                 {0.33, 1,    0.33, 1}, /* high green */
336                 {1,    1,    0.33, 1}, /* high yellow */
337                 {0.33, 0.33, 1,    1}, /* high blue */
338                 {1,    0.33, 1,    1}, /* high magenta */
339                 {0.33, 1,    1,    1}, /* high cyan */
340                 {1,    1,    1,    1}  /* white */
341         },
342         {0, 0, 0, 1},                  /* black border */
343         {7, 0, 0, }                    /* bg:black (0), fg:light gray (7)  */
344 };
345
346 static void
347 terminal_draw_contents(struct terminal *terminal)
348 {
349         struct rectangle rectangle;
350         cairo_t *cr;
351         cairo_font_extents_t extents;
352         int top_margin, side_margin;
353         int row, col;
354         struct attr attr;
355         union utf8_char *p_row;
356         struct utf8_chars {
357                 union utf8_char c;
358                 char null;
359         } toShow;
360         int foreground, background, bold, underline;
361         int text_x, text_y;
362         cairo_surface_t *surface;
363         double d;
364
365         toShow.null = 0;
366
367         window_get_child_rectangle(terminal->window, &rectangle);
368
369         surface = display_create_surface(terminal->display, &rectangle);
370         cr = cairo_create(surface);
371         cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
372         cairo_set_source_rgba(cr,
373                               terminal->color_scheme->border.r,
374                               terminal->color_scheme->border.g,
375                               terminal->color_scheme->border.b,
376                               terminal->color_scheme->border.a);
377         cairo_paint(cr);
378         cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
379
380         cairo_set_font_face(cr, terminal->font_normal);
381         cairo_set_font_size(cr, 14);
382
383         cairo_font_extents(cr, &extents);
384         side_margin = (rectangle.width - terminal->width * extents.max_x_advance) / 2;
385         top_margin = (rectangle.height - terminal->height * extents.height) / 2;
386
387         cairo_set_line_width(cr, 1.0);
388
389         for (row = 0; row < terminal->height; row++) {
390                 p_row = terminal_get_row(terminal, row);
391                 for (col = 0; col < terminal->width; col++) {
392                         /* get the attributes for this character cell */
393                         attr = terminal_get_attr(terminal, row, col);
394                         if ((attr.a & ATTRMASK_INVERSE) ||
395                                 (terminal->focused &&
396                                 terminal->row == row && terminal->column == col))
397                         {
398                                 foreground = attr.bg;
399                                 background = attr.fg;
400                         } else {
401                                 foreground = attr.fg;
402                                 background = attr.bg;
403                         }
404                         bold = attr.a & (ATTRMASK_BOLD | ATTRMASK_BLINK);
405                         underline = attr.a & ATTRMASK_UNDERLINE;
406
407                         /* paint the background */
408                         cairo_set_source_rgba(cr,
409                                               terminal->color_table[background].r,
410                                               terminal->color_table[background].g,
411                                               terminal->color_table[background].b,
412                                               terminal->color_table[background].a);
413                         cairo_move_to(cr, side_margin + (col * extents.max_x_advance),
414                               top_margin + (row * extents.height));
415                         cairo_rel_line_to(cr, extents.max_x_advance, 0);
416                         cairo_rel_line_to(cr, 0, extents.height);
417                         cairo_rel_line_to(cr, -extents.max_x_advance, 0);
418                         cairo_close_path(cr);
419                         cairo_fill(cr);
420
421                         /* paint the foreground */
422                         if (bold)
423                                 cairo_set_font_face(cr, terminal->font_bold);
424                         else
425                                 cairo_set_font_face(cr, terminal->font_normal);
426                         cairo_set_source_rgba(cr,
427                                               terminal->color_table[foreground].r,
428                                               terminal->color_table[foreground].g,
429                                               terminal->color_table[foreground].b,
430                                               terminal->color_table[foreground].a);
431
432                         text_x = side_margin + col * extents.max_x_advance;
433                         text_y = top_margin + extents.ascent + row * extents.height;
434                         if (underline) {
435                                 cairo_move_to(cr, text_x, text_y + 2);
436                                 cairo_line_to(cr, text_x + extents.max_x_advance, text_y + 2);
437                                 cairo_stroke(cr);
438                         }
439                         cairo_move_to(cr, text_x, text_y);
440                         
441                         toShow.c = p_row[col];
442                         cairo_show_text(cr, (char *) toShow.c.byte);
443                 }
444         }
445
446         if (!terminal->focused) {
447                 d = 0.5;
448
449                 cairo_set_line_width(cr, 1);
450                 cairo_move_to(cr, side_margin + terminal->column * extents.max_x_advance + d,
451                               top_margin + terminal->row * extents.height + d);
452                 cairo_rel_line_to(cr, extents.max_x_advance - 2 * d, 0);
453                 cairo_rel_line_to(cr, 0, extents.height - 2 * d);
454                 cairo_rel_line_to(cr, -extents.max_x_advance + 2 * d, 0);
455                 cairo_close_path(cr);
456
457                 cairo_stroke(cr);
458         }
459
460         cairo_destroy(cr);
461
462         window_copy_surface(terminal->window,
463                             &rectangle,
464                             surface);
465
466         cairo_surface_destroy(surface);
467 }
468
469 static void
470 terminal_draw(struct terminal *terminal)
471 {
472         struct rectangle rectangle;
473         int32_t width, height;
474
475         window_get_child_rectangle(terminal->window, &rectangle);
476
477         width = (rectangle.width - 2 * terminal->margin) /
478                 (int32_t) terminal->extents.max_x_advance;
479         height = (rectangle.height - 2 * terminal->margin) /
480                 (int32_t) terminal->extents.height;
481         terminal_resize(terminal, width, height);
482
483         if (!terminal->fullscreen) {
484                 rectangle.width = terminal->width *
485                         terminal->extents.max_x_advance + 2 * terminal->margin;
486                 rectangle.height = terminal->height *
487                         terminal->extents.height + 2 * terminal->margin;
488                 window_set_child_size(terminal->window, &rectangle);
489         }
490
491         window_draw(terminal->window);
492         terminal_draw_contents(terminal);
493         window_flush(terminal->window);
494 }
495
496 static void
497 redraw_handler(struct window *window, void *data)
498 {
499         struct terminal *terminal = data;
500
501         terminal_draw(terminal);
502 }
503
504 #define STATE_NORMAL 0
505 #define STATE_ESCAPE 1
506
507 static void
508 terminal_data(struct terminal *terminal, const char *data, size_t length);
509
510 static void
511 handle_sgr(struct terminal *terminal, int code);
512
513 static void
514 handle_escape(struct terminal *terminal)
515 {
516         union utf8_char *row;
517         struct attr *attr_row;
518         char *p;
519         int i, count;
520         int args[10], set[10] = { 0, };
521
522         terminal->escape[terminal->escape_length++] = '\0';
523         i = 0;
524         p = &terminal->escape[2];
525         while ((isdigit(*p) || *p == ';') && i < 10) {
526                 if (*p == ';') {
527                         if (!set[i]) {
528                                 args[i] = 0;
529                                 set[i] = 1;
530                         }
531                         p++;
532                         i++;
533                 } else {
534                         args[i] = strtol(p, &p, 10);
535                         set[i] = 1;
536                 }
537         }
538         
539         switch (*p) {
540         case 'A':
541                 count = set[0] ? args[0] : 1;
542                 if (terminal->row - count >= 0)
543                         terminal->row -= count;
544                 else
545                         terminal->row = 0;
546                 break;
547         case 'B':
548                 count = set[0] ? args[0] : 1;
549                 if (terminal->row + count < terminal->height)
550                         terminal->row += count;
551                 else
552                         terminal->row = terminal->height;
553                 break;
554         case 'C':
555                 count = set[0] ? args[0] : 1;
556                 if (terminal->column + count < terminal->width)
557                         terminal->column += count;
558                 else
559                         terminal->column = terminal->width;
560                 break;
561         case 'D':
562                 count = set[0] ? args[0] : 1;
563                 if (terminal->column - count >= 0)
564                         terminal->column -= count;
565                 else
566                         terminal->column = 0;
567                 break;
568         case 'J':
569                 row = terminal_get_row(terminal, terminal->row);
570                 attr_row = terminal_get_attr_row(terminal, terminal->row);
571                 memset(&row[terminal->column], 0, (terminal->width - terminal->column) * sizeof(union utf8_char));
572                 attr_init(&attr_row[terminal->column], terminal->curr_attr, (terminal->width - terminal->column));
573                 for (i = terminal->row + 1; i < terminal->height; i++) {
574                         memset(terminal_get_row(terminal, i), 0, terminal->width * sizeof(union utf8_char));
575                         attr_init(terminal_get_attr_row(terminal, i), terminal->curr_attr, terminal->width);
576                 }
577                 break;
578         case 'G':
579                 if (set[0])
580                         terminal->column = args[0] - 1;
581                 break;
582         case 'H':
583         case 'f':
584                 terminal->row = set[0] ? args[0] - 1 : 0;
585                 terminal->column = set[1] ? args[1] - 1 : 0;
586                 break;
587         case 'K':
588                 row = terminal_get_row(terminal, terminal->row);
589                 attr_row = terminal_get_attr_row(terminal, terminal->row);
590                 memset(&row[terminal->column], 0, (terminal->width - terminal->column) * sizeof(union utf8_char));
591                 attr_init(&attr_row[terminal->column], terminal->curr_attr, (terminal->width - terminal->column));
592                 break;
593         case 'm':    /* SGR */
594                 if (set[0] && set[1] && set[2] && args[1] == 5) {
595                         if (args[0] == 38) {
596                                 handle_sgr(terminal, args[2] + 256);
597                                 break;
598                         } else if (args[0] == 48) {
599                                 handle_sgr(terminal, args[2] + 512);
600                                 break;
601                         }
602                 }
603                 for(i = 0; i < 10; i++) {
604                         if(set[i]) {
605                                 handle_sgr(terminal, args[i]);
606                         } else if(i == 0) {
607                                 handle_sgr(terminal, 0);
608                                 break;
609                         } else {
610                                 break;
611                         }
612                 }
613                 break;
614         case '?':
615                 if (strcmp(p, "?25l") == 0) {
616                         /* hide cursor */
617                 } else if (strcmp(p, "?25h") == 0) {
618                         /* show cursor */
619                 }
620                 break;
621         default:
622                 terminal_data(terminal,
623                               terminal->escape + 1,
624                               terminal->escape_length - 2);
625                 break;
626         }       
627 }
628
629 static void
630 handle_sgr(struct terminal *terminal, int code)
631 {
632         switch(code) {
633         case 0:
634                 terminal->curr_attr = terminal->color_scheme->default_attr;
635                 break;
636         case 1:
637                 terminal->curr_attr.a |= ATTRMASK_BOLD;
638                 if (terminal->curr_attr.fg < 8)
639                         terminal->curr_attr.fg += 8;
640                 break;
641         case 4:
642                 terminal->curr_attr.a |= ATTRMASK_UNDERLINE;
643                 break;
644         case 5:
645                 terminal->curr_attr.a |= ATTRMASK_BLINK;
646                 break;
647         case 2:
648         case 21:
649         case 22:
650                 terminal->curr_attr.a &= ~ATTRMASK_BOLD;
651                 if (terminal->curr_attr.fg < 16 && terminal->curr_attr.fg >= 8)
652                         terminal->curr_attr.fg -= 8;
653                 break;
654         case 24:
655                 terminal->curr_attr.a &= ~ATTRMASK_UNDERLINE;
656                 break;
657         case 25:
658                 terminal->curr_attr.a &= ~ATTRMASK_BLINK;
659                 break;
660         case 7:
661         case 26:
662                 terminal->curr_attr.a |= ATTRMASK_INVERSE;
663                 break;
664         case 27:
665                 terminal->curr_attr.a &= ~ATTRMASK_INVERSE;
666                 break;
667         case 39:
668                 terminal->curr_attr.fg = terminal->color_scheme->default_attr.fg;
669                 break;
670         case 49:
671                 terminal->curr_attr.bg = terminal->color_scheme->default_attr.bg;
672                 break;
673         default:
674                 if(code >= 30 && code <= 37) {
675                         terminal->curr_attr.fg = code - 30;
676                         if (terminal->curr_attr.a & ATTRMASK_BOLD)
677                                 terminal->curr_attr.fg += 8;
678                 } else if(code >= 40 && code <= 47) {
679                         terminal->curr_attr.bg = code - 40;
680                 } else if(code >= 256 && code < 512) {
681                         terminal->curr_attr.fg = code - 256;
682                 } else if(code >= 512 && code < 768) {
683                         terminal->curr_attr.bg = code - 512;
684                 } else {
685                         fprintf(stderr, "Unknown SGR code: %d\n", code);
686                 }
687                 break;
688         }
689 }
690
691 static void
692 terminal_data(struct terminal *terminal, const char *data, size_t length)
693 {
694         int i;
695         union utf8_char utf8;
696         enum utf8_state parser_state;
697         union utf8_char *row;
698         struct attr *attr_row;
699
700         for (i = 0; i < length; i++) {
701                 parser_state =
702                         utf8_next_char(&terminal->state_machine, data[i]);
703                 switch(parser_state) {
704                 case utf8state_accept:
705                         utf8.ch = terminal->state_machine.s.ch;
706                         break;
707                 case utf8state_reject:
708                         /* the unicode replacement character */
709                         utf8.byte[0] = 0xEF;
710                         utf8.byte[1] = 0xBF;
711                         utf8.byte[2] = 0xBD;
712                         utf8.byte[3] = 0x00;
713                         break;
714                 default:
715                         continue;
716                 }
717
718                 row = terminal_get_row(terminal, terminal->row);
719                 attr_row = terminal_get_attr_row(terminal, terminal->row);
720
721                 if (terminal->state == STATE_ESCAPE) {
722                         terminal->escape[terminal->escape_length++] = utf8.byte[0];
723                         if (terminal->escape_length == 2 && utf8.byte[0] != '[') {
724                                 /* Bad escape sequence. */
725                                 terminal->state = STATE_NORMAL;
726                                 goto cancel_escape;
727                         }
728
729                         if (isalpha(utf8.byte[0])) {
730                                 terminal->state = STATE_NORMAL;
731                                 handle_escape(terminal);
732                         } 
733                         continue;
734                 }
735
736         cancel_escape:
737                 switch (utf8.byte[0]) {
738                 case '\r':
739                         terminal->column = 0;
740                         break;
741                 case '\n':
742                         terminal->column = 0;
743                         if (terminal->row + 1 < terminal->height) {
744                                 terminal->row++;
745                         } else {
746                                 terminal->start++;
747                                 if (terminal->start == terminal->height)
748                                         terminal->start = 0;
749                                 memset(terminal_get_row(terminal, terminal->row),
750                                        0, terminal->width * sizeof(union utf8_char));
751                                 attr_init(terminal_get_attr_row(terminal, terminal->row),
752                                           terminal->curr_attr, terminal->width);
753                         }
754
755                         break;
756                 case '\t':
757                         memset(&row[terminal->column], ' ', (-terminal->column & 7) * sizeof(union utf8_char));
758                         attr_init(&attr_row[terminal->column], terminal->curr_attr, -terminal->column & 7);
759                         terminal->column = (terminal->column + 7) & ~7;
760                         break;
761                 case '\e':
762                         terminal->state = STATE_ESCAPE;
763                         terminal->escape[0] = '\e';
764                         terminal->escape_length = 1;
765                         break;
766                 case '\b':
767                         if (terminal->column > 0)
768                                 terminal->column--;
769                         break;
770                 case '\a':
771                         /* Bell */
772                         break;
773                 default:
774                         if (terminal->column < terminal->width)
775                                 if (utf8.byte[0] < 32) utf8.byte[0] += 64;
776                         row[terminal->column] = utf8;
777                         attr_row[terminal->column++] = terminal->curr_attr;
778                         break;
779                 }
780         }
781
782         window_schedule_redraw(terminal->window);
783 }
784
785 static void
786 key_handler(struct window *window, uint32_t key, uint32_t sym,
787             uint32_t state, uint32_t modifiers, void *data)
788 {
789         struct terminal *terminal = data;
790         char ch[2];
791         int len = 0;
792
793         switch (sym) {
794         case XK_F11:
795                 if (!state)
796                         break;
797                 terminal->fullscreen ^= 1;
798                 window_set_fullscreen(window, terminal->fullscreen);
799                 window_schedule_redraw(terminal->window);
800                 break;
801
802         case XK_Delete:
803                 sym = 0x04;
804         case XK_BackSpace:
805         case XK_Tab:
806         case XK_Linefeed:
807         case XK_Clear:
808         case XK_Return:
809         case XK_Pause:
810         case XK_Scroll_Lock:
811         case XK_Sys_Req:
812         case XK_Escape:
813                 ch[len++] = sym & 0x7f;
814                 break;
815
816         case XK_Shift_L:
817         case XK_Shift_R:
818         case XK_Control_L:
819         case XK_Control_R:
820         case XK_Alt_L:
821         case XK_Alt_R:
822                 break;
823
824         default:
825                 if (modifiers & WINDOW_MODIFIER_CONTROL)
826                         sym = sym & 0x1f;
827                 else if (modifiers & WINDOW_MODIFIER_ALT)
828                         ch[len++] = 0x1b;
829                 if (sym < 256)
830                         ch[len++] = sym;
831                 break;
832         }
833
834         if (state && len > 0)
835                 write(terminal->master, ch, len);
836 }
837
838 static void
839 keyboard_focus_handler(struct window *window,
840                        struct input *device, void *data)
841 {
842         struct terminal *terminal = data;
843
844         terminal->focused = (device != NULL);
845         window_schedule_redraw(terminal->window);
846 }
847
848 static struct terminal *
849 terminal_create(struct display *display, int fullscreen)
850 {
851         struct terminal *terminal;
852         cairo_surface_t *surface;
853         cairo_t *cr;
854
855         terminal = malloc(sizeof *terminal);
856         if (terminal == NULL)
857                 return terminal;
858
859         memset(terminal, 0, sizeof *terminal);
860         terminal->fullscreen = fullscreen;
861         terminal->color_scheme = &DEFAULT_COLORS;
862         terminal_init(terminal);
863         terminal->window = window_create(display, "Wayland Terminal",
864                                          500, 400);
865
866         init_state_machine(&terminal->state_machine);
867         init_color_table(terminal);
868
869         terminal->display = display;
870         terminal->margin = 5;
871
872         window_set_fullscreen(terminal->window, terminal->fullscreen);
873         window_set_user_data(terminal->window, terminal);
874         window_set_redraw_handler(terminal->window, redraw_handler);
875
876         window_set_key_handler(terminal->window, key_handler);
877         window_set_keyboard_focus_handler(terminal->window,
878                                           keyboard_focus_handler);
879
880         surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
881         cr = cairo_create(surface);
882         terminal->font_bold = cairo_toy_font_face_create ("mono",
883                               CAIRO_FONT_SLANT_NORMAL,
884                               CAIRO_FONT_WEIGHT_BOLD);
885         cairo_font_face_reference(terminal->font_bold);
886         terminal->font_normal = cairo_toy_font_face_create ("mono",
887                                 CAIRO_FONT_SLANT_NORMAL,
888                                 CAIRO_FONT_WEIGHT_NORMAL);
889         cairo_font_face_reference(terminal->font_normal);
890         cairo_set_font_face(cr, terminal->font_normal);
891         cairo_set_font_size(cr, 14);
892         cairo_font_extents(cr, &terminal->extents);
893         cairo_destroy(cr);
894         cairo_surface_destroy(surface);
895
896         terminal_draw(terminal);
897
898         return terminal;
899 }
900
901 static gboolean
902 io_handler(GIOChannel   *source,
903            GIOCondition  condition,
904            gpointer      data)
905 {
906         struct terminal *terminal = data;
907         gchar buffer[256];
908         gsize bytes_read;
909         GError *error = NULL;
910
911         g_io_channel_read_chars(source, buffer, sizeof buffer,
912                                 &bytes_read, &error);
913
914         terminal_data(terminal, buffer, bytes_read);
915
916         return TRUE;
917 }
918
919 static int
920 terminal_run(struct terminal *terminal, const char *path)
921 {
922         int master;
923         pid_t pid;
924
925         pid = forkpty(&master, NULL, NULL, NULL);
926         if (pid == 0) {
927                 setenv("TERM", "vt100", 1);
928                 if (execl(path, path, NULL)) {
929                         printf("exec failed: %m\n");
930                         exit(EXIT_FAILURE);
931                 }
932         } else if (pid < 0) {
933                 fprintf(stderr, "failed to fork and create pty (%m).\n");
934                 return -1;
935         }
936
937         terminal->master = master;
938         terminal->channel = g_io_channel_unix_new(master);
939         fcntl(master, F_SETFL, O_NONBLOCK);
940         g_io_add_watch(terminal->channel, G_IO_IN,
941                        io_handler, terminal);
942
943         return 0;
944 }
945
946 static const GOptionEntry option_entries[] = {
947         { "fullscreen", 'f', 0, G_OPTION_ARG_NONE,
948           &option_fullscreen, "Run in fullscreen mode" },
949         { NULL }
950 };
951
952 int main(int argc, char *argv[])
953 {
954         struct display *d;
955         struct terminal *terminal;
956
957         d = display_create(&argc, &argv, option_entries);
958         if (d == NULL) {
959                 fprintf(stderr, "failed to create display: %m\n");
960                 return -1;
961         }
962
963         terminal = terminal_create(d, option_fullscreen);
964         if (terminal_run(terminal, "/bin/bash"))
965                 exit(EXIT_FAILURE);
966
967         display_run(d);
968
969         return 0;
970 }