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