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