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