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