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