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