Another copy of my dotfiles. Because I don't completely trust GitHub.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2691 lines
56 KiB

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