]> git.armaanb.net Git - st.git/blob - st.c
Split X-specific code into x.c
[st.git] / st.c
1 /* See LICENSE for license details. */
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <locale.h>
7 #include <pwd.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <signal.h>
13 #include <stdint.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <termios.h>
21 #include <time.h>
22 #include <unistd.h>
23 #include <libgen.h>
24 #include <fontconfig/fontconfig.h>
25 #include <wchar.h>
26
27 /* X11 */
28 #include <X11/cursorfont.h>
29 #include <X11/Xft/Xft.h>
30
31 char *argv0;
32
33 #define Glyph Glyph_
34 #define Font Font_
35
36 #include "win.h"
37 #include "st.h"
38
39 #if   defined(__linux)
40  #include <pty.h>
41 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
42  #include <util.h>
43 #elif defined(__FreeBSD__) || defined(__DragonFly__)
44  #include <libutil.h>
45 #endif
46
47 /* Arbitrary sizes */
48 #define UTF_INVALID   0xFFFD
49 #define ESC_BUF_SIZ   (128*UTF_SIZ)
50 #define ESC_ARG_SIZ   16
51 #define STR_BUF_SIZ   ESC_BUF_SIZ
52 #define STR_ARG_SIZ   ESC_ARG_SIZ
53
54 /* macros */
55 #define NUMMAXLEN(x)            ((int)(sizeof(x) * 2.56 + 0.5) + 1)
56 #define DEFAULT(a, b)           (a) = (a) ? (a) : (b)
57 #define ISCONTROLC0(c)          (BETWEEN(c, 0, 0x1f) || (c) == '\177')
58 #define ISCONTROLC1(c)          (BETWEEN(c, 0x80, 0x9f))
59 #define ISCONTROL(c)            (ISCONTROLC0(c) || ISCONTROLC1(c))
60 #define ISDELIM(u)              (utf8strchr(worddelimiters, u) != NULL)
61
62 /* constants */
63 #define ISO14755CMD             "dmenu -w %lu -p codepoint: </dev/null"
64
65 enum cursor_movement {
66         CURSOR_SAVE,
67         CURSOR_LOAD
68 };
69
70 enum cursor_state {
71         CURSOR_DEFAULT  = 0,
72         CURSOR_WRAPNEXT = 1,
73         CURSOR_ORIGIN   = 2
74 };
75
76 enum charset {
77         CS_GRAPHIC0,
78         CS_GRAPHIC1,
79         CS_UK,
80         CS_USA,
81         CS_MULTI,
82         CS_GER,
83         CS_FIN
84 };
85
86 enum escape_state {
87         ESC_START      = 1,
88         ESC_CSI        = 2,
89         ESC_STR        = 4,  /* OSC, PM, APC */
90         ESC_ALTCHARSET = 8,
91         ESC_STR_END    = 16, /* a final string was encountered */
92         ESC_TEST       = 32, /* Enter in test mode */
93         ESC_UTF8       = 64,
94         ESC_DCS        =128,
95 };
96
97 /* CSI Escape sequence structs */
98 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
99 typedef struct {
100         char buf[ESC_BUF_SIZ]; /* raw string */
101         int len;               /* raw string length */
102         char priv;
103         int arg[ESC_ARG_SIZ];
104         int narg;              /* nb of args */
105         char mode[2];
106 } CSIEscape;
107
108 /* STR Escape sequence structs */
109 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
110 typedef struct {
111         char type;             /* ESC type ... */
112         char buf[STR_BUF_SIZ]; /* raw string */
113         int len;               /* raw string length */
114         char *args[STR_ARG_SIZ];
115         int narg;              /* nb of args */
116 } STREscape;
117
118 typedef struct {
119         KeySym k;
120         uint mask;
121         char *s;
122         /* three valued logic variables: 0 indifferent, 1 on, -1 off */
123         signed char appkey;    /* application keypad */
124         signed char appcursor; /* application cursor */
125         signed char crlf;      /* crlf mode          */
126 } Key;
127
128 /* function definitions used in config.h */
129 static void clipcopy(const Arg *);
130 static void clippaste(const Arg *);
131 static void numlock(const Arg *);
132 static void selpaste(const Arg *);
133 static void zoom(const Arg *);
134 static void zoomabs(const Arg *);
135 static void zoomreset(const Arg *);
136 static void printsel(const Arg *);
137 static void printscreen(const Arg *) ;
138 static void iso14755(const Arg *);
139 static void toggleprinter(const Arg *);
140 static void sendbreak(const Arg *);
141
142 /* config.h for applying patches and the configuration. */
143 #include "config.h"
144
145 static void execsh(void);
146 static void stty(void);
147 static void sigchld(int);
148
149 static void csidump(void);
150 static void csihandle(void);
151 static void csiparse(void);
152 static void csireset(void);
153 static int eschandle(uchar);
154 static void strdump(void);
155 static void strhandle(void);
156 static void strparse(void);
157 static void strreset(void);
158
159 static void tprinter(char *, size_t);
160 static void tdumpsel(void);
161 static void tdumpline(int);
162 static void tdump(void);
163 static void tclearregion(int, int, int, int);
164 static void tcursor(int);
165 static void tdeletechar(int);
166 static void tdeleteline(int);
167 static void tinsertblank(int);
168 static void tinsertblankline(int);
169 static int tlinelen(int);
170 static void tmoveto(int, int);
171 static void tmoveato(int, int);
172 static void tnewline(int);
173 static void tputtab(int);
174 static void tputc(Rune);
175 static void treset(void);
176 static void tresize(int, int);
177 static void tscrollup(int, int);
178 static void tscrolldown(int, int);
179 static void tsetattr(int *, int);
180 static void tsetchar(Rune, Glyph *, int, int);
181 static void tsetscroll(int, int);
182 static void tswapscreen(void);
183 static void tsetmode(int, int, int *, int);
184 static void tfulldirt(void);
185 static void techo(Rune);
186 static void tcontrolcode(uchar );
187 static void tdectest(char );
188 static void tdefutf8(char);
189 static int32_t tdefcolor(int *, int *, int);
190 static void tdeftran(char);
191 static void tstrsequence(uchar);
192
193 static void selscroll(int, int);
194 static void selsnap(int *, int *, int);
195
196 static Rune utf8decodebyte(char, size_t *);
197 static char utf8encodebyte(Rune, size_t);
198 static char *utf8strchr(char *s, Rune u);
199 static size_t utf8validate(Rune *, size_t);
200
201 static ssize_t xwrite(int, const char *, size_t);
202 static void *xrealloc(void *, size_t);
203
204 /* Globals */
205 TermWindow win;
206 Term term;
207 Selection sel;
208 int cmdfd;
209 pid_t pid;
210 char **opt_cmd  = NULL;
211 char *opt_class = NULL;
212 char *opt_embed = NULL;
213 char *opt_font  = NULL;
214 char *opt_io    = NULL;
215 char *opt_line  = NULL;
216 char *opt_name  = NULL;
217 char *opt_title = NULL;
218 int oldbutton   = 3; /* button event on startup: 3 = release */
219
220 static CSIEscape csiescseq;
221 static STREscape strescseq;
222 static int iofd = 1;
223
224 char *usedfont = NULL;
225 double usedfontsize = 0;
226 double defaultfontsize = 0;
227
228 static uchar utfbyte[UTF_SIZ + 1] = {0x80,    0, 0xC0, 0xE0, 0xF0};
229 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
230 static Rune utfmin[UTF_SIZ + 1] = {       0,    0,  0x80,  0x800,  0x10000};
231 static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
232
233 /* config.h array lengths */
234 size_t colornamelen = LEN(colorname);
235 size_t mshortcutslen = LEN(mshortcuts);
236 size_t shortcutslen = LEN(shortcuts);
237 size_t selmaskslen = LEN(selmasks);
238
239 ssize_t
240 xwrite(int fd, const char *s, size_t len)
241 {
242         size_t aux = len;
243         ssize_t r;
244
245         while (len > 0) {
246                 r = write(fd, s, len);
247                 if (r < 0)
248                         return r;
249                 len -= r;
250                 s += r;
251         }
252
253         return aux;
254 }
255
256 void *
257 xmalloc(size_t len)
258 {
259         void *p = malloc(len);
260
261         if (!p)
262                 die("Out of memory\n");
263
264         return p;
265 }
266
267 void *
268 xrealloc(void *p, size_t len)
269 {
270         if ((p = realloc(p, len)) == NULL)
271                 die("Out of memory\n");
272
273         return p;
274 }
275
276 char *
277 xstrdup(char *s)
278 {
279         if ((s = strdup(s)) == NULL)
280                 die("Out of memory\n");
281
282         return s;
283 }
284
285 size_t
286 utf8decode(char *c, Rune *u, size_t clen)
287 {
288         size_t i, j, len, type;
289         Rune udecoded;
290
291         *u = UTF_INVALID;
292         if (!clen)
293                 return 0;
294         udecoded = utf8decodebyte(c[0], &len);
295         if (!BETWEEN(len, 1, UTF_SIZ))
296                 return 1;
297         for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
298                 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
299                 if (type != 0)
300                         return j;
301         }
302         if (j < len)
303                 return 0;
304         *u = udecoded;
305         utf8validate(u, len);
306
307         return len;
308 }
309
310 Rune
311 utf8decodebyte(char c, size_t *i)
312 {
313         for (*i = 0; *i < LEN(utfmask); ++(*i))
314                 if (((uchar)c & utfmask[*i]) == utfbyte[*i])
315                         return (uchar)c & ~utfmask[*i];
316
317         return 0;
318 }
319
320 size_t
321 utf8encode(Rune u, char *c)
322 {
323         size_t len, i;
324
325         len = utf8validate(&u, 0);
326         if (len > UTF_SIZ)
327                 return 0;
328
329         for (i = len - 1; i != 0; --i) {
330                 c[i] = utf8encodebyte(u, 0);
331                 u >>= 6;
332         }
333         c[0] = utf8encodebyte(u, len);
334
335         return len;
336 }
337
338 char
339 utf8encodebyte(Rune u, size_t i)
340 {
341         return utfbyte[i] | (u & ~utfmask[i]);
342 }
343
344 char *
345 utf8strchr(char *s, Rune u)
346 {
347         Rune r;
348         size_t i, j, len;
349
350         len = strlen(s);
351         for (i = 0, j = 0; i < len; i += j) {
352                 if (!(j = utf8decode(&s[i], &r, len - i)))
353                         break;
354                 if (r == u)
355                         return &(s[i]);
356         }
357
358         return NULL;
359 }
360
361 size_t
362 utf8validate(Rune *u, size_t i)
363 {
364         if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
365                 *u = UTF_INVALID;
366         for (i = 1; *u > utfmax[i]; ++i)
367                 ;
368
369         return i;
370 }
371
372 void
373 selinit(void)
374 {
375         clock_gettime(CLOCK_MONOTONIC, &sel.tclick1);
376         clock_gettime(CLOCK_MONOTONIC, &sel.tclick2);
377         sel.mode = SEL_IDLE;
378         sel.snap = 0;
379         sel.ob.x = -1;
380         sel.primary = NULL;
381         sel.clipboard = NULL;
382 }
383
384 int
385 x2col(int x)
386 {
387         x -= borderpx;
388         x /= win.cw;
389
390         return LIMIT(x, 0, term.col-1);
391 }
392
393 int
394 y2row(int y)
395 {
396         y -= borderpx;
397         y /= win.ch;
398
399         return LIMIT(y, 0, term.row-1);
400 }
401
402 int
403 tlinelen(int y)
404 {
405         int i = term.col;
406
407         if (term.line[y][i - 1].mode & ATTR_WRAP)
408                 return i;
409
410         while (i > 0 && term.line[y][i - 1].u == ' ')
411                 --i;
412
413         return i;
414 }
415
416 void
417 selnormalize(void)
418 {
419         int i;
420
421         if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
422                 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
423                 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
424         } else {
425                 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
426                 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
427         }
428         sel.nb.y = MIN(sel.ob.y, sel.oe.y);
429         sel.ne.y = MAX(sel.ob.y, sel.oe.y);
430
431         selsnap(&sel.nb.x, &sel.nb.y, -1);
432         selsnap(&sel.ne.x, &sel.ne.y, +1);
433
434         /* expand selection over line breaks */
435         if (sel.type == SEL_RECTANGULAR)
436                 return;
437         i = tlinelen(sel.nb.y);
438         if (i < sel.nb.x)
439                 sel.nb.x = i;
440         if (tlinelen(sel.ne.y) <= sel.ne.x)
441                 sel.ne.x = term.col - 1;
442 }
443
444 int
445 selected(int x, int y)
446 {
447         if (sel.mode == SEL_EMPTY)
448                 return 0;
449
450         if (sel.type == SEL_RECTANGULAR)
451                 return BETWEEN(y, sel.nb.y, sel.ne.y)
452                     && BETWEEN(x, sel.nb.x, sel.ne.x);
453
454         return BETWEEN(y, sel.nb.y, sel.ne.y)
455             && (y != sel.nb.y || x >= sel.nb.x)
456             && (y != sel.ne.y || x <= sel.ne.x);
457 }
458
459 void
460 selsnap(int *x, int *y, int direction)
461 {
462         int newx, newy, xt, yt;
463         int delim, prevdelim;
464         Glyph *gp, *prevgp;
465
466         switch (sel.snap) {
467         case SNAP_WORD:
468                 /*
469                  * Snap around if the word wraps around at the end or
470                  * beginning of a line.
471                  */
472                 prevgp = &term.line[*y][*x];
473                 prevdelim = ISDELIM(prevgp->u);
474                 for (;;) {
475                         newx = *x + direction;
476                         newy = *y;
477                         if (!BETWEEN(newx, 0, term.col - 1)) {
478                                 newy += direction;
479                                 newx = (newx + term.col) % term.col;
480                                 if (!BETWEEN(newy, 0, term.row - 1))
481                                         break;
482
483                                 if (direction > 0)
484                                         yt = *y, xt = *x;
485                                 else
486                                         yt = newy, xt = newx;
487                                 if (!(term.line[yt][xt].mode & ATTR_WRAP))
488                                         break;
489                         }
490
491                         if (newx >= tlinelen(newy))
492                                 break;
493
494                         gp = &term.line[newy][newx];
495                         delim = ISDELIM(gp->u);
496                         if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
497                                         || (delim && gp->u != prevgp->u)))
498                                 break;
499
500                         *x = newx;
501                         *y = newy;
502                         prevgp = gp;
503                         prevdelim = delim;
504                 }
505                 break;
506         case SNAP_LINE:
507                 /*
508                  * Snap around if the the previous line or the current one
509                  * has set ATTR_WRAP at its end. Then the whole next or
510                  * previous line will be selected.
511                  */
512                 *x = (direction < 0) ? 0 : term.col - 1;
513                 if (direction < 0) {
514                         for (; *y > 0; *y += direction) {
515                                 if (!(term.line[*y-1][term.col-1].mode
516                                                 & ATTR_WRAP)) {
517                                         break;
518                                 }
519                         }
520                 } else if (direction > 0) {
521                         for (; *y < term.row-1; *y += direction) {
522                                 if (!(term.line[*y][term.col-1].mode
523                                                 & ATTR_WRAP)) {
524                                         break;
525                                 }
526                         }
527                 }
528                 break;
529         }
530 }
531
532 char *
533 getsel(void)
534 {
535         char *str, *ptr;
536         int y, bufsize, lastx, linelen;
537         Glyph *gp, *last;
538
539         if (sel.ob.x == -1)
540                 return NULL;
541
542         bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
543         ptr = str = xmalloc(bufsize);
544
545         /* append every set & selected glyph to the selection */
546         for (y = sel.nb.y; y <= sel.ne.y; y++) {
547                 if ((linelen = tlinelen(y)) == 0) {
548                         *ptr++ = '\n';
549                         continue;
550                 }
551
552                 if (sel.type == SEL_RECTANGULAR) {
553                         gp = &term.line[y][sel.nb.x];
554                         lastx = sel.ne.x;
555                 } else {
556                         gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
557                         lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
558                 }
559                 last = &term.line[y][MIN(lastx, linelen-1)];
560                 while (last >= gp && last->u == ' ')
561                         --last;
562
563                 for ( ; gp <= last; ++gp) {
564                         if (gp->mode & ATTR_WDUMMY)
565                                 continue;
566
567                         ptr += utf8encode(gp->u, ptr);
568                 }
569
570                 /*
571                  * Copy and pasting of line endings is inconsistent
572                  * in the inconsistent terminal and GUI world.
573                  * The best solution seems like to produce '\n' when
574                  * something is copied from st and convert '\n' to
575                  * '\r', when something to be pasted is received by
576                  * st.
577                  * FIXME: Fix the computer world.
578                  */
579                 if ((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
580                         *ptr++ = '\n';
581         }
582         *ptr = 0;
583         return str;
584 }
585
586 void
587 selpaste(const Arg *dummy)
588 {
589         xselpaste();
590 }
591
592 void
593 clipcopy(const Arg *dummy)
594 {
595         xclipcopy();
596 }
597
598 void
599 clippaste(const Arg *dummy)
600 {
601         xclippaste();
602 }
603
604 void
605 selclear(void)
606 {
607         if (sel.ob.x == -1)
608                 return;
609         sel.mode = SEL_IDLE;
610         sel.ob.x = -1;
611         tsetdirt(sel.nb.y, sel.ne.y);
612 }
613
614 void
615 die(const char *errstr, ...)
616 {
617         va_list ap;
618
619         va_start(ap, errstr);
620         vfprintf(stderr, errstr, ap);
621         va_end(ap);
622         exit(1);
623 }
624
625 void
626 execsh(void)
627 {
628         char **args, *sh, *prog;
629         const struct passwd *pw;
630
631         errno = 0;
632         if ((pw = getpwuid(getuid())) == NULL) {
633                 if (errno)
634                         die("getpwuid:%s\n", strerror(errno));
635                 else
636                         die("who are you?\n");
637         }
638
639         if ((sh = getenv("SHELL")) == NULL)
640                 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
641
642         if (opt_cmd)
643                 prog = opt_cmd[0];
644         else if (utmp)
645                 prog = utmp;
646         else
647                 prog = sh;
648         args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
649
650         unsetenv("COLUMNS");
651         unsetenv("LINES");
652         unsetenv("TERMCAP");
653         setenv("LOGNAME", pw->pw_name, 1);
654         setenv("USER", pw->pw_name, 1);
655         setenv("SHELL", sh, 1);
656         setenv("HOME", pw->pw_dir, 1);
657         setenv("TERM", termname, 1);
658         xsetenv();
659
660         signal(SIGCHLD, SIG_DFL);
661         signal(SIGHUP, SIG_DFL);
662         signal(SIGINT, SIG_DFL);
663         signal(SIGQUIT, SIG_DFL);
664         signal(SIGTERM, SIG_DFL);
665         signal(SIGALRM, SIG_DFL);
666
667         execvp(prog, args);
668         _exit(1);
669 }
670
671 void
672 sigchld(int a)
673 {
674         int stat;
675         pid_t p;
676
677         if ((p = waitpid(pid, &stat, WNOHANG)) < 0)
678                 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
679
680         if (pid != p)
681                 return;
682
683         if (!WIFEXITED(stat) || WEXITSTATUS(stat))
684                 die("child finished with error '%d'\n", stat);
685         exit(0);
686 }
687
688
689 void
690 stty(void)
691 {
692         char cmd[_POSIX_ARG_MAX], **p, *q, *s;
693         size_t n, siz;
694
695         if ((n = strlen(stty_args)) > sizeof(cmd)-1)
696                 die("incorrect stty parameters\n");
697         memcpy(cmd, stty_args, n);
698         q = cmd + n;
699         siz = sizeof(cmd) - n;
700         for (p = opt_cmd; p && (s = *p); ++p) {
701                 if ((n = strlen(s)) > siz-1)
702                         die("stty parameter length too long\n");
703                 *q++ = ' ';
704                 memcpy(q, s, n);
705                 q += n;
706                 siz -= n + 1;
707         }
708         *q = '\0';
709         if (system(cmd) != 0)
710             perror("Couldn't call stty");
711 }
712
713 void
714 ttynew(void)
715 {
716         int m, s;
717         struct winsize w = {term.row, term.col, 0, 0};
718
719         if (opt_io) {
720                 term.mode |= MODE_PRINT;
721                 iofd = (!strcmp(opt_io, "-")) ?
722                           1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
723                 if (iofd < 0) {
724                         fprintf(stderr, "Error opening %s:%s\n",
725                                 opt_io, strerror(errno));
726                 }
727         }
728
729         if (opt_line) {
730                 if ((cmdfd = open(opt_line, O_RDWR)) < 0)
731                         die("open line failed: %s\n", strerror(errno));
732                 dup2(cmdfd, 0);
733                 stty();
734                 return;
735         }
736
737         /* seems to work fine on linux, openbsd and freebsd */
738         if (openpty(&m, &s, NULL, NULL, &w) < 0)
739                 die("openpty failed: %s\n", strerror(errno));
740
741         switch (pid = fork()) {
742         case -1:
743                 die("fork failed\n");
744                 break;
745         case 0:
746                 close(iofd);
747                 setsid(); /* create a new process group */
748                 dup2(s, 0);
749                 dup2(s, 1);
750                 dup2(s, 2);
751                 if (ioctl(s, TIOCSCTTY, NULL) < 0)
752                         die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
753                 close(s);
754                 close(m);
755                 execsh();
756                 break;
757         default:
758                 close(s);
759                 cmdfd = m;
760                 signal(SIGCHLD, sigchld);
761                 break;
762         }
763 }
764
765 size_t
766 ttyread(void)
767 {
768         static char buf[BUFSIZ];
769         static int buflen = 0;
770         char *ptr;
771         int charsize; /* size of utf8 char in bytes */
772         Rune unicodep;
773         int ret;
774
775         /* append read bytes to unprocessed bytes */
776         if ((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
777                 die("Couldn't read from shell: %s\n", strerror(errno));
778
779         buflen += ret;
780         ptr = buf;
781
782         for (;;) {
783                 if (IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
784                         /* process a complete utf8 char */
785                         charsize = utf8decode(ptr, &unicodep, buflen);
786                         if (charsize == 0)
787                                 break;
788                         tputc(unicodep);
789                         ptr += charsize;
790                         buflen -= charsize;
791
792                 } else {
793                         if (buflen <= 0)
794                                 break;
795                         tputc(*ptr++ & 0xFF);
796                         buflen--;
797                 }
798         }
799         /* keep any uncomplete utf8 char for the next call */
800         if (buflen > 0)
801                 memmove(buf, ptr, buflen);
802
803         return ret;
804 }
805
806 void
807 ttywrite(const char *s, size_t n)
808 {
809         fd_set wfd, rfd;
810         ssize_t r;
811         size_t lim = 256;
812
813         /*
814          * Remember that we are using a pty, which might be a modem line.
815          * Writing too much will clog the line. That's why we are doing this
816          * dance.
817          * FIXME: Migrate the world to Plan 9.
818          */
819         while (n > 0) {
820                 FD_ZERO(&wfd);
821                 FD_ZERO(&rfd);
822                 FD_SET(cmdfd, &wfd);
823                 FD_SET(cmdfd, &rfd);
824
825                 /* Check if we can write. */
826                 if (pselect(cmdfd+1, &rfd, &wfd, NULL, NULL, NULL) < 0) {
827                         if (errno == EINTR)
828                                 continue;
829                         die("select failed: %s\n", strerror(errno));
830                 }
831                 if (FD_ISSET(cmdfd, &wfd)) {
832                         /*
833                          * Only write the bytes written by ttywrite() or the
834                          * default of 256. This seems to be a reasonable value
835                          * for a serial line. Bigger values might clog the I/O.
836                          */
837                         if ((r = write(cmdfd, s, (n < lim)? n : lim)) < 0)
838                                 goto write_error;
839                         if (r < n) {
840                                 /*
841                                  * We weren't able to write out everything.
842                                  * This means the buffer is getting full
843                                  * again. Empty it.
844                                  */
845                                 if (n < lim)
846                                         lim = ttyread();
847                                 n -= r;
848                                 s += r;
849                         } else {
850                                 /* All bytes have been written. */
851                                 break;
852                         }
853                 }
854                 if (FD_ISSET(cmdfd, &rfd))
855                         lim = ttyread();
856         }
857         return;
858
859 write_error:
860         die("write error on tty: %s\n", strerror(errno));
861 }
862
863 void
864 ttysend(char *s, size_t n)
865 {
866         int len;
867         char *t, *lim;
868         Rune u;
869
870         ttywrite(s, n);
871         if (!IS_SET(MODE_ECHO))
872                 return;
873
874         lim = &s[n];
875         for (t = s; t < lim; t += len) {
876                 if (IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
877                         len = utf8decode(t, &u, n);
878                 } else {
879                         u = *t & 0xFF;
880                         len = 1;
881                 }
882                 if (len <= 0)
883                         break;
884                 techo(u);
885                 n -= len;
886         }
887 }
888
889 void
890 ttyresize(void)
891 {
892         struct winsize w;
893
894         w.ws_row = term.row;
895         w.ws_col = term.col;
896         w.ws_xpixel = win.tw;
897         w.ws_ypixel = win.th;
898         if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
899                 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
900 }
901
902 int
903 tattrset(int attr)
904 {
905         int i, j;
906
907         for (i = 0; i < term.row-1; i++) {
908                 for (j = 0; j < term.col-1; j++) {
909                         if (term.line[i][j].mode & attr)
910                                 return 1;
911                 }
912         }
913
914         return 0;
915 }
916
917 void
918 tsetdirt(int top, int bot)
919 {
920         int i;
921
922         LIMIT(top, 0, term.row-1);
923         LIMIT(bot, 0, term.row-1);
924
925         for (i = top; i <= bot; i++)
926                 term.dirty[i] = 1;
927 }
928
929 void
930 tsetdirtattr(int attr)
931 {
932         int i, j;
933
934         for (i = 0; i < term.row-1; i++) {
935                 for (j = 0; j < term.col-1; j++) {
936                         if (term.line[i][j].mode & attr) {
937                                 tsetdirt(i, i);
938                                 break;
939                         }
940                 }
941         }
942 }
943
944 void
945 tfulldirt(void)
946 {
947         tsetdirt(0, term.row-1);
948 }
949
950 void
951 tcursor(int mode)
952 {
953         static TCursor c[2];
954         int alt = IS_SET(MODE_ALTSCREEN);
955
956         if (mode == CURSOR_SAVE) {
957                 c[alt] = term.c;
958         } else if (mode == CURSOR_LOAD) {
959                 term.c = c[alt];
960                 tmoveto(c[alt].x, c[alt].y);
961         }
962 }
963
964 void
965 treset(void)
966 {
967         uint i;
968
969         term.c = (TCursor){{
970                 .mode = ATTR_NULL,
971                 .fg = defaultfg,
972                 .bg = defaultbg
973         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
974
975         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
976         for (i = tabspaces; i < term.col; i += tabspaces)
977                 term.tabs[i] = 1;
978         term.top = 0;
979         term.bot = term.row - 1;
980         term.mode = MODE_WRAP|MODE_UTF8;
981         memset(term.trantbl, CS_USA, sizeof(term.trantbl));
982         term.charset = 0;
983
984         for (i = 0; i < 2; i++) {
985                 tmoveto(0, 0);
986                 tcursor(CURSOR_SAVE);
987                 tclearregion(0, 0, term.col-1, term.row-1);
988                 tswapscreen();
989         }
990 }
991
992 void
993 tnew(int col, int row)
994 {
995         term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
996         tresize(col, row);
997         term.numlock = 1;
998
999         treset();
1000 }
1001
1002 void
1003 tswapscreen(void)
1004 {
1005         Line *tmp = term.line;
1006
1007         term.line = term.alt;
1008         term.alt = tmp;
1009         term.mode ^= MODE_ALTSCREEN;
1010         tfulldirt();
1011 }
1012
1013 void
1014 tscrolldown(int orig, int n)
1015 {
1016         int i;
1017         Line temp;
1018
1019         LIMIT(n, 0, term.bot-orig+1);
1020
1021         tsetdirt(orig, term.bot-n);
1022         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1023
1024         for (i = term.bot; i >= orig+n; i--) {
1025                 temp = term.line[i];
1026                 term.line[i] = term.line[i-n];
1027                 term.line[i-n] = temp;
1028         }
1029
1030         selscroll(orig, n);
1031 }
1032
1033 void
1034 tscrollup(int orig, int n)
1035 {
1036         int i;
1037         Line temp;
1038
1039         LIMIT(n, 0, term.bot-orig+1);
1040
1041         tclearregion(0, orig, term.col-1, orig+n-1);
1042         tsetdirt(orig+n, term.bot);
1043
1044         for (i = orig; i <= term.bot-n; i++) {
1045                 temp = term.line[i];
1046                 term.line[i] = term.line[i+n];
1047                 term.line[i+n] = temp;
1048         }
1049
1050         selscroll(orig, -n);
1051 }
1052
1053 void
1054 selscroll(int orig, int n)
1055 {
1056         if (sel.ob.x == -1)
1057                 return;
1058
1059         if (BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1060                 if ((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1061                         selclear();
1062                         return;
1063                 }
1064                 if (sel.type == SEL_RECTANGULAR) {
1065                         if (sel.ob.y < term.top)
1066                                 sel.ob.y = term.top;
1067                         if (sel.oe.y > term.bot)
1068                                 sel.oe.y = term.bot;
1069                 } else {
1070                         if (sel.ob.y < term.top) {
1071                                 sel.ob.y = term.top;
1072                                 sel.ob.x = 0;
1073                         }
1074                         if (sel.oe.y > term.bot) {
1075                                 sel.oe.y = term.bot;
1076                                 sel.oe.x = term.col;
1077                         }
1078                 }
1079                 selnormalize();
1080         }
1081 }
1082
1083 void
1084 tnewline(int first_col)
1085 {
1086         int y = term.c.y;
1087
1088         if (y == term.bot) {
1089                 tscrollup(term.top, 1);
1090         } else {
1091                 y++;
1092         }
1093         tmoveto(first_col ? 0 : term.c.x, y);
1094 }
1095
1096 void
1097 csiparse(void)
1098 {
1099         char *p = csiescseq.buf, *np;
1100         long int v;
1101
1102         csiescseq.narg = 0;
1103         if (*p == '?') {
1104                 csiescseq.priv = 1;
1105                 p++;
1106         }
1107
1108         csiescseq.buf[csiescseq.len] = '\0';
1109         while (p < csiescseq.buf+csiescseq.len) {
1110                 np = NULL;
1111                 v = strtol(p, &np, 10);
1112                 if (np == p)
1113                         v = 0;
1114                 if (v == LONG_MAX || v == LONG_MIN)
1115                         v = -1;
1116                 csiescseq.arg[csiescseq.narg++] = v;
1117                 p = np;
1118                 if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1119                         break;
1120                 p++;
1121         }
1122         csiescseq.mode[0] = *p++;
1123         csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1124 }
1125
1126 /* for absolute user moves, when decom is set */
1127 void
1128 tmoveato(int x, int y)
1129 {
1130         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1131 }
1132
1133 void
1134 tmoveto(int x, int y)
1135 {
1136         int miny, maxy;
1137
1138         if (term.c.state & CURSOR_ORIGIN) {
1139                 miny = term.top;
1140                 maxy = term.bot;
1141         } else {
1142                 miny = 0;
1143                 maxy = term.row - 1;
1144         }
1145         term.c.state &= ~CURSOR_WRAPNEXT;
1146         term.c.x = LIMIT(x, 0, term.col-1);
1147         term.c.y = LIMIT(y, miny, maxy);
1148 }
1149
1150 void
1151 tsetchar(Rune u, Glyph *attr, int x, int y)
1152 {
1153         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1154                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1155                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1156                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1157                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1158                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1159                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1160                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1161                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1162         };
1163
1164         /*
1165          * The table is proudly stolen from rxvt.
1166          */
1167         if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
1168            BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1169                 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1170
1171         if (term.line[y][x].mode & ATTR_WIDE) {
1172                 if (x+1 < term.col) {
1173                         term.line[y][x+1].u = ' ';
1174                         term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1175                 }
1176         } else if (term.line[y][x].mode & ATTR_WDUMMY) {
1177                 term.line[y][x-1].u = ' ';
1178                 term.line[y][x-1].mode &= ~ATTR_WIDE;
1179         }
1180
1181         term.dirty[y] = 1;
1182         term.line[y][x] = *attr;
1183         term.line[y][x].u = u;
1184 }
1185
1186 void
1187 tclearregion(int x1, int y1, int x2, int y2)
1188 {
1189         int x, y, temp;
1190         Glyph *gp;
1191
1192         if (x1 > x2)
1193                 temp = x1, x1 = x2, x2 = temp;
1194         if (y1 > y2)
1195                 temp = y1, y1 = y2, y2 = temp;
1196
1197         LIMIT(x1, 0, term.col-1);
1198         LIMIT(x2, 0, term.col-1);
1199         LIMIT(y1, 0, term.row-1);
1200         LIMIT(y2, 0, term.row-1);
1201
1202         for (y = y1; y <= y2; y++) {
1203                 term.dirty[y] = 1;
1204                 for (x = x1; x <= x2; x++) {
1205                         gp = &term.line[y][x];
1206                         if (selected(x, y))
1207                                 selclear();
1208                         gp->fg = term.c.attr.fg;
1209                         gp->bg = term.c.attr.bg;
1210                         gp->mode = 0;
1211                         gp->u = ' ';
1212                 }
1213         }
1214 }
1215
1216 void
1217 tdeletechar(int n)
1218 {
1219         int dst, src, size;
1220         Glyph *line;
1221
1222         LIMIT(n, 0, term.col - term.c.x);
1223
1224         dst = term.c.x;
1225         src = term.c.x + n;
1226         size = term.col - src;
1227         line = term.line[term.c.y];
1228
1229         memmove(&line[dst], &line[src], size * sizeof(Glyph));
1230         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1231 }
1232
1233 void
1234 tinsertblank(int n)
1235 {
1236         int dst, src, size;
1237         Glyph *line;
1238
1239         LIMIT(n, 0, term.col - term.c.x);
1240
1241         dst = term.c.x + n;
1242         src = term.c.x;
1243         size = term.col - dst;
1244         line = term.line[term.c.y];
1245
1246         memmove(&line[dst], &line[src], size * sizeof(Glyph));
1247         tclearregion(src, term.c.y, dst - 1, term.c.y);
1248 }
1249
1250 void
1251 tinsertblankline(int n)
1252 {
1253         if (BETWEEN(term.c.y, term.top, term.bot))
1254                 tscrolldown(term.c.y, n);
1255 }
1256
1257 void
1258 tdeleteline(int n)
1259 {
1260         if (BETWEEN(term.c.y, term.top, term.bot))
1261                 tscrollup(term.c.y, n);
1262 }
1263
1264 int32_t
1265 tdefcolor(int *attr, int *npar, int l)
1266 {
1267         int32_t idx = -1;
1268         uint r, g, b;
1269
1270         switch (attr[*npar + 1]) {
1271         case 2: /* direct color in RGB space */
1272                 if (*npar + 4 >= l) {
1273                         fprintf(stderr,
1274                                 "erresc(38): Incorrect number of parameters (%d)\n",
1275                                 *npar);
1276                         break;
1277                 }
1278                 r = attr[*npar + 2];
1279                 g = attr[*npar + 3];
1280                 b = attr[*npar + 4];
1281                 *npar += 4;
1282                 if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1283                         fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1284                                 r, g, b);
1285                 else
1286                         idx = TRUECOLOR(r, g, b);
1287                 break;
1288         case 5: /* indexed color */
1289                 if (*npar + 2 >= l) {
1290                         fprintf(stderr,
1291                                 "erresc(38): Incorrect number of parameters (%d)\n",
1292                                 *npar);
1293                         break;
1294                 }
1295                 *npar += 2;
1296                 if (!BETWEEN(attr[*npar], 0, 255))
1297                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1298                 else
1299                         idx = attr[*npar];
1300                 break;
1301         case 0: /* implemented defined (only foreground) */
1302         case 1: /* transparent */
1303         case 3: /* direct color in CMY space */
1304         case 4: /* direct color in CMYK space */
1305         default:
1306                 fprintf(stderr,
1307                         "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1308                 break;
1309         }
1310
1311         return idx;
1312 }
1313
1314 void
1315 tsetattr(int *attr, int l)
1316 {
1317         int i;
1318         int32_t idx;
1319
1320         for (i = 0; i < l; i++) {
1321                 switch (attr[i]) {
1322                 case 0:
1323                         term.c.attr.mode &= ~(
1324                                 ATTR_BOLD       |
1325                                 ATTR_FAINT      |
1326                                 ATTR_ITALIC     |
1327                                 ATTR_UNDERLINE  |
1328                                 ATTR_BLINK      |
1329                                 ATTR_REVERSE    |
1330                                 ATTR_INVISIBLE  |
1331                                 ATTR_STRUCK     );
1332                         term.c.attr.fg = defaultfg;
1333                         term.c.attr.bg = defaultbg;
1334                         break;
1335                 case 1:
1336                         term.c.attr.mode |= ATTR_BOLD;
1337                         break;
1338                 case 2:
1339                         term.c.attr.mode |= ATTR_FAINT;
1340                         break;
1341                 case 3:
1342                         term.c.attr.mode |= ATTR_ITALIC;
1343                         break;
1344                 case 4:
1345                         term.c.attr.mode |= ATTR_UNDERLINE;
1346                         break;
1347                 case 5: /* slow blink */
1348                         /* FALLTHROUGH */
1349                 case 6: /* rapid blink */
1350                         term.c.attr.mode |= ATTR_BLINK;
1351                         break;
1352                 case 7:
1353                         term.c.attr.mode |= ATTR_REVERSE;
1354                         break;
1355                 case 8:
1356                         term.c.attr.mode |= ATTR_INVISIBLE;
1357                         break;
1358                 case 9:
1359                         term.c.attr.mode |= ATTR_STRUCK;
1360                         break;
1361                 case 22:
1362                         term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
1363                         break;
1364                 case 23:
1365                         term.c.attr.mode &= ~ATTR_ITALIC;
1366                         break;
1367                 case 24:
1368                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1369                         break;
1370                 case 25:
1371                         term.c.attr.mode &= ~ATTR_BLINK;
1372                         break;
1373                 case 27:
1374                         term.c.attr.mode &= ~ATTR_REVERSE;
1375                         break;
1376                 case 28:
1377                         term.c.attr.mode &= ~ATTR_INVISIBLE;
1378                         break;
1379                 case 29:
1380                         term.c.attr.mode &= ~ATTR_STRUCK;
1381                         break;
1382                 case 38:
1383                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
1384                                 term.c.attr.fg = idx;
1385                         break;
1386                 case 39:
1387                         term.c.attr.fg = defaultfg;
1388                         break;
1389                 case 48:
1390                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
1391                                 term.c.attr.bg = idx;
1392                         break;
1393                 case 49:
1394                         term.c.attr.bg = defaultbg;
1395                         break;
1396                 default:
1397                         if (BETWEEN(attr[i], 30, 37)) {
1398                                 term.c.attr.fg = attr[i] - 30;
1399                         } else if (BETWEEN(attr[i], 40, 47)) {
1400                                 term.c.attr.bg = attr[i] - 40;
1401                         } else if (BETWEEN(attr[i], 90, 97)) {
1402                                 term.c.attr.fg = attr[i] - 90 + 8;
1403                         } else if (BETWEEN(attr[i], 100, 107)) {
1404                                 term.c.attr.bg = attr[i] - 100 + 8;
1405                         } else {
1406                                 fprintf(stderr,
1407                                         "erresc(default): gfx attr %d unknown\n",
1408                                         attr[i]), csidump();
1409                         }
1410                         break;
1411                 }
1412         }
1413 }
1414
1415 void
1416 tsetscroll(int t, int b)
1417 {
1418         int temp;
1419
1420         LIMIT(t, 0, term.row-1);
1421         LIMIT(b, 0, term.row-1);
1422         if (t > b) {
1423                 temp = t;
1424                 t = b;
1425                 b = temp;
1426         }
1427         term.top = t;
1428         term.bot = b;
1429 }
1430
1431 void
1432 tsetmode(int priv, int set, int *args, int narg)
1433 {
1434         int *lim, mode;
1435         int alt;
1436
1437         for (lim = args + narg; args < lim; ++args) {
1438                 if (priv) {
1439                         switch (*args) {
1440                         case 1: /* DECCKM -- Cursor key */
1441                                 MODBIT(term.mode, set, MODE_APPCURSOR);
1442                                 break;
1443                         case 5: /* DECSCNM -- Reverse video */
1444                                 mode = term.mode;
1445                                 MODBIT(term.mode, set, MODE_REVERSE);
1446                                 if (mode != term.mode)
1447                                         redraw();
1448                                 break;
1449                         case 6: /* DECOM -- Origin */
1450                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1451                                 tmoveato(0, 0);
1452                                 break;
1453                         case 7: /* DECAWM -- Auto wrap */
1454                                 MODBIT(term.mode, set, MODE_WRAP);
1455                                 break;
1456                         case 0:  /* Error (IGNORED) */
1457                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
1458                         case 3:  /* DECCOLM -- Column  (IGNORED) */
1459                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
1460                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
1461                         case 18: /* DECPFF -- Printer feed (IGNORED) */
1462                         case 19: /* DECPEX -- Printer extent (IGNORED) */
1463                         case 42: /* DECNRCM -- National characters (IGNORED) */
1464                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1465                                 break;
1466                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1467                                 MODBIT(term.mode, !set, MODE_HIDE);
1468                                 break;
1469                         case 9:    /* X10 mouse compatibility mode */
1470                                 xsetpointermotion(0);
1471                                 MODBIT(term.mode, 0, MODE_MOUSE);
1472                                 MODBIT(term.mode, set, MODE_MOUSEX10);
1473                                 break;
1474                         case 1000: /* 1000: report button press */
1475                                 xsetpointermotion(0);
1476                                 MODBIT(term.mode, 0, MODE_MOUSE);
1477                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1478                                 break;
1479                         case 1002: /* 1002: report motion on button press */
1480                                 xsetpointermotion(0);
1481                                 MODBIT(term.mode, 0, MODE_MOUSE);
1482                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1483                                 break;
1484                         case 1003: /* 1003: enable all mouse motions */
1485                                 xsetpointermotion(set);
1486                                 MODBIT(term.mode, 0, MODE_MOUSE);
1487                                 MODBIT(term.mode, set, MODE_MOUSEMANY);
1488                                 break;
1489                         case 1004: /* 1004: send focus events to tty */
1490                                 MODBIT(term.mode, set, MODE_FOCUS);
1491                                 break;
1492                         case 1006: /* 1006: extended reporting mode */
1493                                 MODBIT(term.mode, set, MODE_MOUSESGR);
1494                                 break;
1495                         case 1034:
1496                                 MODBIT(term.mode, set, MODE_8BIT);
1497                                 break;
1498                         case 1049: /* swap screen & set/restore cursor as xterm */
1499                                 if (!allowaltscreen)
1500                                         break;
1501                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1502                                 /* FALLTHROUGH */
1503                         case 47: /* swap screen */
1504                         case 1047:
1505                                 if (!allowaltscreen)
1506                                         break;
1507                                 alt = IS_SET(MODE_ALTSCREEN);
1508                                 if (alt) {
1509                                         tclearregion(0, 0, term.col-1,
1510                                                         term.row-1);
1511                                 }
1512                                 if (set ^ alt) /* set is always 1 or 0 */
1513                                         tswapscreen();
1514                                 if (*args != 1049)
1515                                         break;
1516                                 /* FALLTHROUGH */
1517                         case 1048:
1518                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1519                                 break;
1520                         case 2004: /* 2004: bracketed paste mode */
1521                                 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1522                                 break;
1523                         /* Not implemented mouse modes. See comments there. */
1524                         case 1001: /* mouse highlight mode; can hang the
1525                                       terminal by design when implemented. */
1526                         case 1005: /* UTF-8 mouse mode; will confuse
1527                                       applications not supporting UTF-8
1528                                       and luit. */
1529                         case 1015: /* urxvt mangled mouse mode; incompatible
1530                                       and can be mistaken for other control
1531                                       codes. */
1532                         default:
1533                                 fprintf(stderr,
1534                                         "erresc: unknown private set/reset mode %d\n",
1535                                         *args);
1536                                 break;
1537                         }
1538                 } else {
1539                         switch (*args) {
1540                         case 0:  /* Error (IGNORED) */
1541                                 break;
1542                         case 2:  /* KAM -- keyboard action */
1543                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1544                                 break;
1545                         case 4:  /* IRM -- Insertion-replacement */
1546                                 MODBIT(term.mode, set, MODE_INSERT);
1547                                 break;
1548                         case 12: /* SRM -- Send/Receive */
1549                                 MODBIT(term.mode, !set, MODE_ECHO);
1550                                 break;
1551                         case 20: /* LNM -- Linefeed/new line */
1552                                 MODBIT(term.mode, set, MODE_CRLF);
1553                                 break;
1554                         default:
1555                                 fprintf(stderr,
1556                                         "erresc: unknown set/reset mode %d\n",
1557                                         *args);
1558                                 break;
1559                         }
1560                 }
1561         }
1562 }
1563
1564 void
1565 csihandle(void)
1566 {
1567         char buf[40];
1568         int len;
1569
1570         switch (csiescseq.mode[0]) {
1571         default:
1572         unknown:
1573                 fprintf(stderr, "erresc: unknown csi ");
1574                 csidump();
1575                 /* die(""); */
1576                 break;
1577         case '@': /* ICH -- Insert <n> blank char */
1578                 DEFAULT(csiescseq.arg[0], 1);
1579                 tinsertblank(csiescseq.arg[0]);
1580                 break;
1581         case 'A': /* CUU -- Cursor <n> Up */
1582                 DEFAULT(csiescseq.arg[0], 1);
1583                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1584                 break;
1585         case 'B': /* CUD -- Cursor <n> Down */
1586         case 'e': /* VPR --Cursor <n> Down */
1587                 DEFAULT(csiescseq.arg[0], 1);
1588                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1589                 break;
1590         case 'i': /* MC -- Media Copy */
1591                 switch (csiescseq.arg[0]) {
1592                 case 0:
1593                         tdump();
1594                         break;
1595                 case 1:
1596                         tdumpline(term.c.y);
1597                         break;
1598                 case 2:
1599                         tdumpsel();
1600                         break;
1601                 case 4:
1602                         term.mode &= ~MODE_PRINT;
1603                         break;
1604                 case 5:
1605                         term.mode |= MODE_PRINT;
1606                         break;
1607                 }
1608                 break;
1609         case 'c': /* DA -- Device Attributes */
1610                 if (csiescseq.arg[0] == 0)
1611                         ttywrite(vtiden, sizeof(vtiden) - 1);
1612                 break;
1613         case 'C': /* CUF -- Cursor <n> Forward */
1614         case 'a': /* HPR -- Cursor <n> Forward */
1615                 DEFAULT(csiescseq.arg[0], 1);
1616                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1617                 break;
1618         case 'D': /* CUB -- Cursor <n> Backward */
1619                 DEFAULT(csiescseq.arg[0], 1);
1620                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1621                 break;
1622         case 'E': /* CNL -- Cursor <n> Down and first col */
1623                 DEFAULT(csiescseq.arg[0], 1);
1624                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1625                 break;
1626         case 'F': /* CPL -- Cursor <n> Up and first col */
1627                 DEFAULT(csiescseq.arg[0], 1);
1628                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1629                 break;
1630         case 'g': /* TBC -- Tabulation clear */
1631                 switch (csiescseq.arg[0]) {
1632                 case 0: /* clear current tab stop */
1633                         term.tabs[term.c.x] = 0;
1634                         break;
1635                 case 3: /* clear all the tabs */
1636                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1637                         break;
1638                 default:
1639                         goto unknown;
1640                 }
1641                 break;
1642         case 'G': /* CHA -- Move to <col> */
1643         case '`': /* HPA */
1644                 DEFAULT(csiescseq.arg[0], 1);
1645                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1646                 break;
1647         case 'H': /* CUP -- Move to <row> <col> */
1648         case 'f': /* HVP */
1649                 DEFAULT(csiescseq.arg[0], 1);
1650                 DEFAULT(csiescseq.arg[1], 1);
1651                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1652                 break;
1653         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1654                 DEFAULT(csiescseq.arg[0], 1);
1655                 tputtab(csiescseq.arg[0]);
1656                 break;
1657         case 'J': /* ED -- Clear screen */
1658                 selclear();
1659                 switch (csiescseq.arg[0]) {
1660                 case 0: /* below */
1661                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1662                         if (term.c.y < term.row-1) {
1663                                 tclearregion(0, term.c.y+1, term.col-1,
1664                                                 term.row-1);
1665                         }
1666                         break;
1667                 case 1: /* above */
1668                         if (term.c.y > 1)
1669                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1670                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1671                         break;
1672                 case 2: /* all */
1673                         tclearregion(0, 0, term.col-1, term.row-1);
1674                         break;
1675                 default:
1676                         goto unknown;
1677                 }
1678                 break;
1679         case 'K': /* EL -- Clear line */
1680                 switch (csiescseq.arg[0]) {
1681                 case 0: /* right */
1682                         tclearregion(term.c.x, term.c.y, term.col-1,
1683                                         term.c.y);
1684                         break;
1685                 case 1: /* left */
1686                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1687                         break;
1688                 case 2: /* all */
1689                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1690                         break;
1691                 }
1692                 break;
1693         case 'S': /* SU -- Scroll <n> line up */
1694                 DEFAULT(csiescseq.arg[0], 1);
1695                 tscrollup(term.top, csiescseq.arg[0]);
1696                 break;
1697         case 'T': /* SD -- Scroll <n> line down */
1698                 DEFAULT(csiescseq.arg[0], 1);
1699                 tscrolldown(term.top, csiescseq.arg[0]);
1700                 break;
1701         case 'L': /* IL -- Insert <n> blank lines */
1702                 DEFAULT(csiescseq.arg[0], 1);
1703                 tinsertblankline(csiescseq.arg[0]);
1704                 break;
1705         case 'l': /* RM -- Reset Mode */
1706                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1707                 break;
1708         case 'M': /* DL -- Delete <n> lines */
1709                 DEFAULT(csiescseq.arg[0], 1);
1710                 tdeleteline(csiescseq.arg[0]);
1711                 break;
1712         case 'X': /* ECH -- Erase <n> char */
1713                 DEFAULT(csiescseq.arg[0], 1);
1714                 tclearregion(term.c.x, term.c.y,
1715                                 term.c.x + csiescseq.arg[0] - 1, term.c.y);
1716                 break;
1717         case 'P': /* DCH -- Delete <n> char */
1718                 DEFAULT(csiescseq.arg[0], 1);
1719                 tdeletechar(csiescseq.arg[0]);
1720                 break;
1721         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1722                 DEFAULT(csiescseq.arg[0], 1);
1723                 tputtab(-csiescseq.arg[0]);
1724                 break;
1725         case 'd': /* VPA -- Move to <row> */
1726                 DEFAULT(csiescseq.arg[0], 1);
1727                 tmoveato(term.c.x, csiescseq.arg[0]-1);
1728                 break;
1729         case 'h': /* SM -- Set terminal mode */
1730                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1731                 break;
1732         case 'm': /* SGR -- Terminal attribute (color) */
1733                 tsetattr(csiescseq.arg, csiescseq.narg);
1734                 break;
1735         case 'n': /* DSR – Device Status Report (cursor position) */
1736                 if (csiescseq.arg[0] == 6) {
1737                         len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
1738                                         term.c.y+1, term.c.x+1);
1739                         ttywrite(buf, len);
1740                 }
1741                 break;
1742         case 'r': /* DECSTBM -- Set Scrolling Region */
1743                 if (csiescseq.priv) {
1744                         goto unknown;
1745                 } else {
1746                         DEFAULT(csiescseq.arg[0], 1);
1747                         DEFAULT(csiescseq.arg[1], term.row);
1748                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1749                         tmoveato(0, 0);
1750                 }
1751                 break;
1752         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1753                 tcursor(CURSOR_SAVE);
1754                 break;
1755         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1756                 tcursor(CURSOR_LOAD);
1757                 break;
1758         case ' ':
1759                 switch (csiescseq.mode[1]) {
1760                 case 'q': /* DECSCUSR -- Set Cursor Style */
1761                         DEFAULT(csiescseq.arg[0], 1);
1762                         if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
1763                                 goto unknown;
1764                         }
1765                         win.cursor = csiescseq.arg[0];
1766                         break;
1767                 default:
1768                         goto unknown;
1769                 }
1770                 break;
1771         }
1772 }
1773
1774 void
1775 csidump(void)
1776 {
1777         int i;
1778         uint c;
1779
1780         fprintf(stderr, "ESC[");
1781         for (i = 0; i < csiescseq.len; i++) {
1782                 c = csiescseq.buf[i] & 0xff;
1783                 if (isprint(c)) {
1784                         putc(c, stderr);
1785                 } else if (c == '\n') {
1786                         fprintf(stderr, "(\\n)");
1787                 } else if (c == '\r') {
1788                         fprintf(stderr, "(\\r)");
1789                 } else if (c == 0x1b) {
1790                         fprintf(stderr, "(\\e)");
1791                 } else {
1792                         fprintf(stderr, "(%02x)", c);
1793                 }
1794         }
1795         putc('\n', stderr);
1796 }
1797
1798 void
1799 csireset(void)
1800 {
1801         memset(&csiescseq, 0, sizeof(csiescseq));
1802 }
1803
1804 void
1805 strhandle(void)
1806 {
1807         char *p = NULL;
1808         int j, narg, par;
1809
1810         term.esc &= ~(ESC_STR_END|ESC_STR);
1811         strparse();
1812         par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
1813
1814         switch (strescseq.type) {
1815         case ']': /* OSC -- Operating System Command */
1816                 switch (par) {
1817                 case 0:
1818                 case 1:
1819                 case 2:
1820                         if (narg > 1)
1821                                 xsettitle(strescseq.args[1]);
1822                         return;
1823                 case 4: /* color set */
1824                         if (narg < 3)
1825                                 break;
1826                         p = strescseq.args[2];
1827                         /* FALLTHROUGH */
1828                 case 104: /* color reset, here p = NULL */
1829                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
1830                         if (xsetcolorname(j, p)) {
1831                                 fprintf(stderr, "erresc: invalid color %s\n", p);
1832                         } else {
1833                                 /*
1834                                  * TODO if defaultbg color is changed, borders
1835                                  * are dirty
1836                                  */
1837                                 redraw();
1838                         }
1839                         return;
1840                 }
1841                 break;
1842         case 'k': /* old title set compatibility */
1843                 xsettitle(strescseq.args[0]);
1844                 return;
1845         case 'P': /* DCS -- Device Control String */
1846                 term.mode |= ESC_DCS;
1847         case '_': /* APC -- Application Program Command */
1848         case '^': /* PM -- Privacy Message */
1849                 return;
1850         }
1851
1852         fprintf(stderr, "erresc: unknown str ");
1853         strdump();
1854 }
1855
1856 void
1857 strparse(void)
1858 {
1859         int c;
1860         char *p = strescseq.buf;
1861
1862         strescseq.narg = 0;
1863         strescseq.buf[strescseq.len] = '\0';
1864
1865         if (*p == '\0')
1866                 return;
1867
1868         while (strescseq.narg < STR_ARG_SIZ) {
1869                 strescseq.args[strescseq.narg++] = p;
1870                 while ((c = *p) != ';' && c != '\0')
1871                         ++p;
1872                 if (c == '\0')
1873                         return;
1874                 *p++ = '\0';
1875         }
1876 }
1877
1878 void
1879 strdump(void)
1880 {
1881         int i;
1882         uint c;
1883
1884         fprintf(stderr, "ESC%c", strescseq.type);
1885         for (i = 0; i < strescseq.len; i++) {
1886                 c = strescseq.buf[i] & 0xff;
1887                 if (c == '\0') {
1888                         putc('\n', stderr);
1889                         return;
1890                 } else if (isprint(c)) {
1891                         putc(c, stderr);
1892                 } else if (c == '\n') {
1893                         fprintf(stderr, "(\\n)");
1894                 } else if (c == '\r') {
1895                         fprintf(stderr, "(\\r)");
1896                 } else if (c == 0x1b) {
1897                         fprintf(stderr, "(\\e)");
1898                 } else {
1899                         fprintf(stderr, "(%02x)", c);
1900                 }
1901         }
1902         fprintf(stderr, "ESC\\\n");
1903 }
1904
1905 void
1906 strreset(void)
1907 {
1908         memset(&strescseq, 0, sizeof(strescseq));
1909 }
1910
1911 void
1912 sendbreak(const Arg *arg)
1913 {
1914         if (tcsendbreak(cmdfd, 0))
1915                 perror("Error sending break");
1916 }
1917
1918 void
1919 tprinter(char *s, size_t len)
1920 {
1921         if (iofd != -1 && xwrite(iofd, s, len) < 0) {
1922                 fprintf(stderr, "Error writing in %s:%s\n",
1923                         opt_io, strerror(errno));
1924                 close(iofd);
1925                 iofd = -1;
1926         }
1927 }
1928
1929 void
1930 iso14755(const Arg *arg)
1931 {
1932         unsigned long id = xwinid();
1933         char cmd[sizeof(ISO14755CMD) + NUMMAXLEN(id)];
1934         FILE *p;
1935         char *us, *e, codepoint[9], uc[UTF_SIZ];
1936         unsigned long utf32;
1937
1938         snprintf(cmd, sizeof(cmd), ISO14755CMD, id);
1939         if (!(p = popen(cmd, "r")))
1940                 return;
1941
1942         us = fgets(codepoint, sizeof(codepoint), p);
1943         pclose(p);
1944
1945         if (!us || *us == '\0' || *us == '-' || strlen(us) > 7)
1946                 return;
1947         if ((utf32 = strtoul(us, &e, 16)) == ULONG_MAX ||
1948             (*e != '\n' && *e != '\0'))
1949                 return;
1950
1951         ttysend(uc, utf8encode(utf32, uc));
1952 }
1953
1954 void
1955 toggleprinter(const Arg *arg)
1956 {
1957         term.mode ^= MODE_PRINT;
1958 }
1959
1960 void
1961 printscreen(const Arg *arg)
1962 {
1963         tdump();
1964 }
1965
1966 void
1967 printsel(const Arg *arg)
1968 {
1969         tdumpsel();
1970 }
1971
1972 void
1973 tdumpsel(void)
1974 {
1975         char *ptr;
1976
1977         if ((ptr = getsel())) {
1978                 tprinter(ptr, strlen(ptr));
1979                 free(ptr);
1980         }
1981 }
1982
1983 void
1984 tdumpline(int n)
1985 {
1986         char buf[UTF_SIZ];
1987         Glyph *bp, *end;
1988
1989         bp = &term.line[n][0];
1990         end = &bp[MIN(tlinelen(n), term.col) - 1];
1991         if (bp != end || bp->u != ' ') {
1992                 for ( ;bp <= end; ++bp)
1993                         tprinter(buf, utf8encode(bp->u, buf));
1994         }
1995         tprinter("\n", 1);
1996 }
1997
1998 void
1999 tdump(void)
2000 {
2001         int i;
2002
2003         for (i = 0; i < term.row; ++i)
2004                 tdumpline(i);
2005 }
2006
2007 void
2008 tputtab(int n)
2009 {
2010         uint x = term.c.x;
2011
2012         if (n > 0) {
2013                 while (x < term.col && n--)
2014                         for (++x; x < term.col && !term.tabs[x]; ++x)
2015                                 /* nothing */ ;
2016         } else if (n < 0) {
2017                 while (x > 0 && n++)
2018                         for (--x; x > 0 && !term.tabs[x]; --x)
2019                                 /* nothing */ ;
2020         }
2021         term.c.x = LIMIT(x, 0, term.col-1);
2022 }
2023
2024 void
2025 techo(Rune u)
2026 {
2027         if (ISCONTROL(u)) { /* control code */
2028                 if (u & 0x80) {
2029                         u &= 0x7f;
2030                         tputc('^');
2031                         tputc('[');
2032                 } else if (u != '\n' && u != '\r' && u != '\t') {
2033                         u ^= 0x40;
2034                         tputc('^');
2035                 }
2036         }
2037         tputc(u);
2038 }
2039
2040 void
2041 tdefutf8(char ascii)
2042 {
2043         if (ascii == 'G')
2044                 term.mode |= MODE_UTF8;
2045         else if (ascii == '@')
2046                 term.mode &= ~MODE_UTF8;
2047 }
2048
2049 void
2050 tdeftran(char ascii)
2051 {
2052         static char cs[] = "0B";
2053         static int vcs[] = {CS_GRAPHIC0, CS_USA};
2054         char *p;
2055
2056         if ((p = strchr(cs, ascii)) == NULL) {
2057                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2058         } else {
2059                 term.trantbl[term.icharset] = vcs[p - cs];
2060         }
2061 }
2062
2063 void
2064 tdectest(char c)
2065 {
2066         int x, y;
2067
2068         if (c == '8') { /* DEC screen alignment test. */
2069                 for (x = 0; x < term.col; ++x) {
2070                         for (y = 0; y < term.row; ++y)
2071                                 tsetchar('E', &term.c.attr, x, y);
2072                 }
2073         }
2074 }
2075
2076 void
2077 tstrsequence(uchar c)
2078 {
2079         strreset();
2080
2081         switch (c) {
2082         case 0x90:   /* DCS -- Device Control String */
2083                 c = 'P';
2084                 term.esc |= ESC_DCS;
2085                 break;
2086         case 0x9f:   /* APC -- Application Program Command */
2087                 c = '_';
2088                 break;
2089         case 0x9e:   /* PM -- Privacy Message */
2090                 c = '^';
2091                 break;
2092         case 0x9d:   /* OSC -- Operating System Command */
2093                 c = ']';
2094                 break;
2095         }
2096         strescseq.type = c;
2097         term.esc |= ESC_STR;
2098 }
2099
2100 void
2101 tcontrolcode(uchar ascii)
2102 {
2103         switch (ascii) {
2104         case '\t':   /* HT */
2105                 tputtab(1);
2106                 return;
2107         case '\b':   /* BS */
2108                 tmoveto(term.c.x-1, term.c.y);
2109                 return;
2110         case '\r':   /* CR */
2111                 tmoveto(0, term.c.y);
2112                 return;
2113         case '\f':   /* LF */
2114         case '\v':   /* VT */
2115         case '\n':   /* LF */
2116                 /* go to first col if the mode is set */
2117                 tnewline(IS_SET(MODE_CRLF));
2118                 return;
2119         case '\a':   /* BEL */
2120                 if (term.esc & ESC_STR_END) {
2121                         /* backwards compatibility to xterm */
2122                         strhandle();
2123                 } else {
2124                         if (!(win.state & WIN_FOCUSED))
2125                                 xseturgency(1);
2126                         if (bellvolume)
2127                                 xbell(bellvolume);
2128                 }
2129                 break;
2130         case '\033': /* ESC */
2131                 csireset();
2132                 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2133                 term.esc |= ESC_START;
2134                 return;
2135         case '\016': /* SO (LS1 -- Locking shift 1) */
2136         case '\017': /* SI (LS0 -- Locking shift 0) */
2137                 term.charset = 1 - (ascii - '\016');
2138                 return;
2139         case '\032': /* SUB */
2140                 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2141         case '\030': /* CAN */
2142                 csireset();
2143                 break;
2144         case '\005': /* ENQ (IGNORED) */
2145         case '\000': /* NUL (IGNORED) */
2146         case '\021': /* XON (IGNORED) */
2147         case '\023': /* XOFF (IGNORED) */
2148         case 0177:   /* DEL (IGNORED) */
2149                 return;
2150         case 0x80:   /* TODO: PAD */
2151         case 0x81:   /* TODO: HOP */
2152         case 0x82:   /* TODO: BPH */
2153         case 0x83:   /* TODO: NBH */
2154         case 0x84:   /* TODO: IND */
2155                 break;
2156         case 0x85:   /* NEL -- Next line */
2157                 tnewline(1); /* always go to first col */
2158                 break;
2159         case 0x86:   /* TODO: SSA */
2160         case 0x87:   /* TODO: ESA */
2161                 break;
2162         case 0x88:   /* HTS -- Horizontal tab stop */
2163                 term.tabs[term.c.x] = 1;
2164                 break;
2165         case 0x89:   /* TODO: HTJ */
2166         case 0x8a:   /* TODO: VTS */
2167         case 0x8b:   /* TODO: PLD */
2168         case 0x8c:   /* TODO: PLU */
2169         case 0x8d:   /* TODO: RI */
2170         case 0x8e:   /* TODO: SS2 */
2171         case 0x8f:   /* TODO: SS3 */
2172         case 0x91:   /* TODO: PU1 */
2173         case 0x92:   /* TODO: PU2 */
2174         case 0x93:   /* TODO: STS */
2175         case 0x94:   /* TODO: CCH */
2176         case 0x95:   /* TODO: MW */
2177         case 0x96:   /* TODO: SPA */
2178         case 0x97:   /* TODO: EPA */
2179         case 0x98:   /* TODO: SOS */
2180         case 0x99:   /* TODO: SGCI */
2181                 break;
2182         case 0x9a:   /* DECID -- Identify Terminal */
2183                 ttywrite(vtiden, sizeof(vtiden) - 1);
2184                 break;
2185         case 0x9b:   /* TODO: CSI */
2186         case 0x9c:   /* TODO: ST */
2187                 break;
2188         case 0x90:   /* DCS -- Device Control String */
2189         case 0x9d:   /* OSC -- Operating System Command */
2190         case 0x9e:   /* PM -- Privacy Message */
2191         case 0x9f:   /* APC -- Application Program Command */
2192                 tstrsequence(ascii);
2193                 return;
2194         }
2195         /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2196         term.esc &= ~(ESC_STR_END|ESC_STR);
2197 }
2198
2199 /*
2200  * returns 1 when the sequence is finished and it hasn't to read
2201  * more characters for this sequence, otherwise 0
2202  */
2203 int
2204 eschandle(uchar ascii)
2205 {
2206         switch (ascii) {
2207         case '[':
2208                 term.esc |= ESC_CSI;
2209                 return 0;
2210         case '#':
2211                 term.esc |= ESC_TEST;
2212                 return 0;
2213         case '%':
2214                 term.esc |= ESC_UTF8;
2215                 return 0;
2216         case 'P': /* DCS -- Device Control String */
2217         case '_': /* APC -- Application Program Command */
2218         case '^': /* PM -- Privacy Message */
2219         case ']': /* OSC -- Operating System Command */
2220         case 'k': /* old title set compatibility */
2221                 tstrsequence(ascii);
2222                 return 0;
2223         case 'n': /* LS2 -- Locking shift 2 */
2224         case 'o': /* LS3 -- Locking shift 3 */
2225                 term.charset = 2 + (ascii - 'n');
2226                 break;
2227         case '(': /* GZD4 -- set primary charset G0 */
2228         case ')': /* G1D4 -- set secondary charset G1 */
2229         case '*': /* G2D4 -- set tertiary charset G2 */
2230         case '+': /* G3D4 -- set quaternary charset G3 */
2231                 term.icharset = ascii - '(';
2232                 term.esc |= ESC_ALTCHARSET;
2233                 return 0;
2234         case 'D': /* IND -- Linefeed */
2235                 if (term.c.y == term.bot) {
2236                         tscrollup(term.top, 1);
2237                 } else {
2238                         tmoveto(term.c.x, term.c.y+1);
2239                 }
2240                 break;
2241         case 'E': /* NEL -- Next line */
2242                 tnewline(1); /* always go to first col */
2243                 break;
2244         case 'H': /* HTS -- Horizontal tab stop */
2245                 term.tabs[term.c.x] = 1;
2246                 break;
2247         case 'M': /* RI -- Reverse index */
2248                 if (term.c.y == term.top) {
2249                         tscrolldown(term.top, 1);
2250                 } else {
2251                         tmoveto(term.c.x, term.c.y-1);
2252                 }
2253                 break;
2254         case 'Z': /* DECID -- Identify Terminal */
2255                 ttywrite(vtiden, sizeof(vtiden) - 1);
2256                 break;
2257         case 'c': /* RIS -- Reset to inital state */
2258                 treset();
2259                 resettitle();
2260                 xloadcols();
2261                 break;
2262         case '=': /* DECPAM -- Application keypad */
2263                 term.mode |= MODE_APPKEYPAD;
2264                 break;
2265         case '>': /* DECPNM -- Normal keypad */
2266                 term.mode &= ~MODE_APPKEYPAD;
2267                 break;
2268         case '7': /* DECSC -- Save Cursor */
2269                 tcursor(CURSOR_SAVE);
2270                 break;
2271         case '8': /* DECRC -- Restore Cursor */
2272                 tcursor(CURSOR_LOAD);
2273                 break;
2274         case '\\': /* ST -- String Terminator */
2275                 if (term.esc & ESC_STR_END)
2276                         strhandle();
2277                 break;
2278         default:
2279                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2280                         (uchar) ascii, isprint(ascii)? ascii:'.');
2281                 break;
2282         }
2283         return 1;
2284 }
2285
2286 void
2287 tputc(Rune u)
2288 {
2289         char c[UTF_SIZ];
2290         int control;
2291         int width, len;
2292         Glyph *gp;
2293
2294         control = ISCONTROL(u);
2295         if (!IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
2296                 c[0] = u;
2297                 width = len = 1;
2298         } else {
2299                 len = utf8encode(u, c);
2300                 if (!control && (width = wcwidth(u)) == -1) {
2301                         memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
2302                         width = 1;
2303                 }
2304         }
2305
2306         if (IS_SET(MODE_PRINT))
2307                 tprinter(c, len);
2308
2309         /*
2310          * STR sequence must be checked before anything else
2311          * because it uses all following characters until it
2312          * receives a ESC, a SUB, a ST or any other C1 control
2313          * character.
2314          */
2315         if (term.esc & ESC_STR) {
2316                 if (u == '\a' || u == 030 || u == 032 || u == 033 ||
2317                    ISCONTROLC1(u)) {
2318                         term.esc &= ~(ESC_START|ESC_STR|ESC_DCS);
2319                         if (IS_SET(MODE_SIXEL)) {
2320                                 /* TODO: render sixel */;
2321                                 term.mode &= ~MODE_SIXEL;
2322                                 return;
2323                         }
2324                         term.esc |= ESC_STR_END;
2325                         goto check_control_code;
2326                 }
2327
2328
2329                 if (IS_SET(MODE_SIXEL)) {
2330                         /* TODO: implement sixel mode */
2331                         return;
2332                 }
2333                 if (term.esc&ESC_DCS && strescseq.len == 0 && u == 'q')
2334                         term.mode |= MODE_SIXEL;
2335
2336                 if (strescseq.len+len >= sizeof(strescseq.buf)-1) {
2337                         /*
2338                          * Here is a bug in terminals. If the user never sends
2339                          * some code to stop the str or esc command, then st
2340                          * will stop responding. But this is better than
2341                          * silently failing with unknown characters. At least
2342                          * then users will report back.
2343                          *
2344                          * In the case users ever get fixed, here is the code:
2345                          */
2346                         /*
2347                          * term.esc = 0;
2348                          * strhandle();
2349                          */
2350                         return;
2351                 }
2352
2353                 memmove(&strescseq.buf[strescseq.len], c, len);
2354                 strescseq.len += len;
2355                 return;
2356         }
2357
2358 check_control_code:
2359         /*
2360          * Actions of control codes must be performed as soon they arrive
2361          * because they can be embedded inside a control sequence, and
2362          * they must not cause conflicts with sequences.
2363          */
2364         if (control) {
2365                 tcontrolcode(u);
2366                 /*
2367                  * control codes are not shown ever
2368                  */
2369                 return;
2370         } else if (term.esc & ESC_START) {
2371                 if (term.esc & ESC_CSI) {
2372                         csiescseq.buf[csiescseq.len++] = u;
2373                         if (BETWEEN(u, 0x40, 0x7E)
2374                                         || csiescseq.len >= \
2375                                         sizeof(csiescseq.buf)-1) {
2376                                 term.esc = 0;
2377                                 csiparse();
2378                                 csihandle();
2379                         }
2380                         return;
2381                 } else if (term.esc & ESC_UTF8) {
2382                         tdefutf8(u);
2383                 } else if (term.esc & ESC_ALTCHARSET) {
2384                         tdeftran(u);
2385                 } else if (term.esc & ESC_TEST) {
2386                         tdectest(u);
2387                 } else {
2388                         if (!eschandle(u))
2389                                 return;
2390                         /* sequence already finished */
2391                 }
2392                 term.esc = 0;
2393                 /*
2394                  * All characters which form part of a sequence are not
2395                  * printed
2396                  */
2397                 return;
2398         }
2399         if (sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2400                 selclear();
2401
2402         gp = &term.line[term.c.y][term.c.x];
2403         if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2404                 gp->mode |= ATTR_WRAP;
2405                 tnewline(1);
2406                 gp = &term.line[term.c.y][term.c.x];
2407         }
2408
2409         if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
2410                 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
2411
2412         if (term.c.x+width > term.col) {
2413                 tnewline(1);
2414                 gp = &term.line[term.c.y][term.c.x];
2415         }
2416
2417         tsetchar(u, &term.c.attr, term.c.x, term.c.y);
2418
2419         if (width == 2) {
2420                 gp->mode |= ATTR_WIDE;
2421                 if (term.c.x+1 < term.col) {
2422                         gp[1].u = '\0';
2423                         gp[1].mode = ATTR_WDUMMY;
2424                 }
2425         }
2426         if (term.c.x+width < term.col) {
2427                 tmoveto(term.c.x+width, term.c.y);
2428         } else {
2429                 term.c.state |= CURSOR_WRAPNEXT;
2430         }
2431 }
2432
2433 void
2434 tresize(int col, int row)
2435 {
2436         int i;
2437         int minrow = MIN(row, term.row);
2438         int mincol = MIN(col, term.col);
2439         int *bp;
2440         TCursor c;
2441
2442         if (col < 1 || row < 1) {
2443                 fprintf(stderr,
2444                         "tresize: error resizing to %dx%d\n", col, row);
2445                 return;
2446         }
2447
2448         /*
2449          * slide screen to keep cursor where we expect it -
2450          * tscrollup would work here, but we can optimize to
2451          * memmove because we're freeing the earlier lines
2452          */
2453         for (i = 0; i <= term.c.y - row; i++) {
2454                 free(term.line[i]);
2455                 free(term.alt[i]);
2456         }
2457         /* ensure that both src and dst are not NULL */
2458         if (i > 0) {
2459                 memmove(term.line, term.line + i, row * sizeof(Line));
2460                 memmove(term.alt, term.alt + i, row * sizeof(Line));
2461         }
2462         for (i += row; i < term.row; i++) {
2463                 free(term.line[i]);
2464                 free(term.alt[i]);
2465         }
2466
2467         /* resize to new width */
2468         term.specbuf = xrealloc(term.specbuf, col * sizeof(GlyphFontSpec));
2469
2470         /* resize to new height */
2471         term.line = xrealloc(term.line, row * sizeof(Line));
2472         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2473         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2474         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2475
2476         /* resize each row to new width, zero-pad if needed */
2477         for (i = 0; i < minrow; i++) {
2478                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2479                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2480         }
2481
2482         /* allocate any new rows */
2483         for (/* i == minrow */; i < row; i++) {
2484                 term.line[i] = xmalloc(col * sizeof(Glyph));
2485                 term.alt[i] = xmalloc(col * sizeof(Glyph));
2486         }
2487         if (col > term.col) {
2488                 bp = term.tabs + term.col;
2489
2490                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2491                 while (--bp > term.tabs && !*bp)
2492                         /* nothing */ ;
2493                 for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2494                         *bp = 1;
2495         }
2496         /* update terminal size */
2497         term.col = col;
2498         term.row = row;
2499         /* reset scrolling region */
2500         tsetscroll(0, row-1);
2501         /* make use of the LIMIT in tmoveto */
2502         tmoveto(term.c.x, term.c.y);
2503         /* Clearing both screens (it makes dirty all lines) */
2504         c = term.c;
2505         for (i = 0; i < 2; i++) {
2506                 if (mincol < col && 0 < minrow) {
2507                         tclearregion(mincol, 0, col - 1, minrow - 1);
2508                 }
2509                 if (0 < col && minrow < row) {
2510                         tclearregion(0, minrow, col - 1, row - 1);
2511                 }
2512                 tswapscreen();
2513                 tcursor(CURSOR_LOAD);
2514         }
2515         term.c = c;
2516 }
2517
2518 void
2519 zoom(const Arg *arg)
2520 {
2521         Arg larg;
2522
2523         larg.f = usedfontsize + arg->f;
2524         zoomabs(&larg);
2525 }
2526
2527 void
2528 zoomabs(const Arg *arg)
2529 {
2530         xunloadfonts();
2531         xloadfonts(usedfont, arg->f);
2532         cresize(0, 0);
2533         ttyresize();
2534         redraw();
2535         xhints();
2536 }
2537
2538 void
2539 zoomreset(const Arg *arg)
2540 {
2541         Arg larg;
2542
2543         if (defaultfontsize > 0) {
2544                 larg.f = defaultfontsize;
2545                 zoomabs(&larg);
2546         }
2547 }
2548
2549 void
2550 resettitle(void)
2551 {
2552         xsettitle(opt_title ? opt_title : "st");
2553 }
2554
2555 void
2556 redraw(void)
2557 {
2558         tfulldirt();
2559         draw();
2560 }
2561
2562 int
2563 match(uint mask, uint state)
2564 {
2565         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
2566 }
2567
2568 void
2569 numlock(const Arg *dummy)
2570 {
2571         term.numlock ^= 1;
2572 }
2573
2574 char*
2575 kmap(KeySym k, uint state)
2576 {
2577         Key *kp;
2578         int i;
2579
2580         /* Check for mapped keys out of X11 function keys. */
2581         for (i = 0; i < LEN(mappedkeys); i++) {
2582                 if (mappedkeys[i] == k)
2583                         break;
2584         }
2585         if (i == LEN(mappedkeys)) {
2586                 if ((k & 0xFFFF) < 0xFD00)
2587                         return NULL;
2588         }
2589
2590         for (kp = key; kp < key + LEN(key); kp++) {
2591                 if (kp->k != k)
2592                         continue;
2593
2594                 if (!match(kp->mask, state))
2595                         continue;
2596
2597                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
2598                         continue;
2599                 if (term.numlock && kp->appkey == 2)
2600                         continue;
2601
2602                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
2603                         continue;
2604
2605                 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
2606                         continue;
2607
2608                 return kp->s;
2609         }
2610
2611         return NULL;
2612 }
2613
2614 void
2615 cresize(int width, int height)
2616 {
2617         int col, row;
2618
2619         if (width != 0)
2620                 win.w = width;
2621         if (height != 0)
2622                 win.h = height;
2623
2624         col = (win.w - 2 * borderpx) / win.cw;
2625         row = (win.h - 2 * borderpx) / win.ch;
2626
2627         tresize(col, row);
2628         xresize(col, row);
2629 }
2630
2631 void
2632 usage(void)
2633 {
2634         die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2635             " [-n name] [-o file]\n"
2636             "          [-T title] [-t title] [-w windowid]"
2637             " [[-e] command [args ...]]\n"
2638             "       %s [-aiv] [-c class] [-f font] [-g geometry]"
2639             " [-n name] [-o file]\n"
2640             "          [-T title] [-t title] [-w windowid] -l line"
2641             " [stty_args ...]\n", argv0, argv0);
2642 }