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