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.

2694 lines
56 KiB

4 years ago
4 years ago
4 years ago
4 years ago
  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. if (isboxdraw(u))
  1068. term.line[y][x].mode |= ATTR_BOXDRAW;
  1069. }
  1070. void
  1071. tclearregion(int x1, int y1, int x2, int y2)
  1072. {
  1073. int x, y, temp;
  1074. Glyph *gp;
  1075. if (x1 > x2)
  1076. temp = x1, x1 = x2, x2 = temp;
  1077. if (y1 > y2)
  1078. temp = y1, y1 = y2, y2 = temp;
  1079. LIMIT(x1, 0, term.col-1);
  1080. LIMIT(x2, 0, term.col-1);
  1081. LIMIT(y1, 0, term.row-1);
  1082. LIMIT(y2, 0, term.row-1);
  1083. for (y = y1; y <= y2; y++) {
  1084. term.dirty[y] = 1;
  1085. for (x = x1; x <= x2; x++) {
  1086. gp = &term.line[y][x];
  1087. if (selected(x, y))
  1088. selclear();
  1089. gp->fg = term.c.attr.fg;
  1090. gp->bg = term.c.attr.bg;
  1091. gp->mode = 0;
  1092. gp->u = ' ';
  1093. }
  1094. }
  1095. }
  1096. void
  1097. tdeletechar(int n)
  1098. {
  1099. int dst, src, size;
  1100. Glyph *line;
  1101. LIMIT(n, 0, term.col - term.c.x);
  1102. dst = term.c.x;
  1103. src = term.c.x + n;
  1104. size = term.col - src;
  1105. line = term.line[term.c.y];
  1106. memmove(&line[dst], &line[src], size * sizeof(Glyph));
  1107. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1108. }
  1109. void
  1110. tinsertblank(int n)
  1111. {
  1112. int dst, src, size;
  1113. Glyph *line;
  1114. LIMIT(n, 0, term.col - term.c.x);
  1115. dst = term.c.x + n;
  1116. src = term.c.x;
  1117. size = term.col - dst;
  1118. line = term.line[term.c.y];
  1119. memmove(&line[dst], &line[src], size * sizeof(Glyph));
  1120. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1121. }
  1122. void
  1123. tinsertblankline(int n)
  1124. {
  1125. if (BETWEEN(term.c.y, term.top, term.bot))
  1126. tscrolldown(term.c.y, n);
  1127. }
  1128. void
  1129. tdeleteline(int n)
  1130. {
  1131. if (BETWEEN(term.c.y, term.top, term.bot))
  1132. tscrollup(term.c.y, n);
  1133. }
  1134. int32_t
  1135. tdefcolor(int *attr, int *npar, int l)
  1136. {
  1137. int32_t idx = -1;
  1138. uint r, g, b;
  1139. switch (attr[*npar + 1]) {
  1140. case 2: /* direct color in RGB space */
  1141. if (*npar + 4 >= l) {
  1142. fprintf(stderr,
  1143. "erresc(38): Incorrect number of parameters (%d)\n",
  1144. *npar);
  1145. break;
  1146. }
  1147. r = attr[*npar + 2];
  1148. g = attr[*npar + 3];
  1149. b = attr[*npar + 4];
  1150. *npar += 4;
  1151. if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
  1152. fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
  1153. r, g, b);
  1154. else
  1155. idx = TRUECOLOR(r, g, b);
  1156. break;
  1157. case 5: /* indexed color */
  1158. if (*npar + 2 >= l) {
  1159. fprintf(stderr,
  1160. "erresc(38): Incorrect number of parameters (%d)\n",
  1161. *npar);
  1162. break;
  1163. }
  1164. *npar += 2;
  1165. if (!BETWEEN(attr[*npar], 0, 255))
  1166. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
  1167. else
  1168. idx = attr[*npar];
  1169. break;
  1170. case 0: /* implemented defined (only foreground) */
  1171. case 1: /* transparent */
  1172. case 3: /* direct color in CMY space */
  1173. case 4: /* direct color in CMYK space */
  1174. default:
  1175. fprintf(stderr,
  1176. "erresc(38): gfx attr %d unknown\n", attr[*npar]);
  1177. break;
  1178. }
  1179. return idx;
  1180. }
  1181. void
  1182. tsetattr(int *attr, int l)
  1183. {
  1184. int i;
  1185. int32_t idx;
  1186. for (i = 0; i < l; i++) {
  1187. switch (attr[i]) {
  1188. case 0:
  1189. term.c.attr.mode &= ~(
  1190. ATTR_BOLD |
  1191. ATTR_FAINT |
  1192. ATTR_ITALIC |
  1193. ATTR_UNDERLINE |
  1194. ATTR_BLINK |
  1195. ATTR_REVERSE |
  1196. ATTR_INVISIBLE |
  1197. ATTR_STRUCK );
  1198. term.c.attr.fg = defaultfg;
  1199. term.c.attr.bg = defaultbg;
  1200. break;
  1201. case 1:
  1202. term.c.attr.mode |= ATTR_BOLD;
  1203. break;
  1204. case 2:
  1205. term.c.attr.mode |= ATTR_FAINT;
  1206. break;
  1207. case 3:
  1208. term.c.attr.mode |= ATTR_ITALIC;
  1209. break;
  1210. case 4:
  1211. term.c.attr.mode |= ATTR_UNDERLINE;
  1212. break;
  1213. case 5: /* slow blink */
  1214. /* FALLTHROUGH */
  1215. case 6: /* rapid blink */
  1216. term.c.attr.mode |= ATTR_BLINK;
  1217. break;
  1218. case 7:
  1219. term.c.attr.mode |= ATTR_REVERSE;
  1220. break;
  1221. case 8:
  1222. term.c.attr.mode |= ATTR_INVISIBLE;
  1223. break;
  1224. case 9:
  1225. term.c.attr.mode |= ATTR_STRUCK;
  1226. break;
  1227. case 22:
  1228. term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
  1229. break;
  1230. case 23:
  1231. term.c.attr.mode &= ~ATTR_ITALIC;
  1232. break;
  1233. case 24:
  1234. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1235. break;
  1236. case 25:
  1237. term.c.attr.mode &= ~ATTR_BLINK;
  1238. break;
  1239. case 27:
  1240. term.c.attr.mode &= ~ATTR_REVERSE;
  1241. break;
  1242. case 28:
  1243. term.c.attr.mode &= ~ATTR_INVISIBLE;
  1244. break;
  1245. case 29:
  1246. term.c.attr.mode &= ~ATTR_STRUCK;
  1247. break;
  1248. case 38:
  1249. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1250. term.c.attr.fg = idx;
  1251. break;
  1252. case 39:
  1253. term.c.attr.fg = defaultfg;
  1254. break;
  1255. case 48:
  1256. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1257. term.c.attr.bg = idx;
  1258. break;
  1259. case 49:
  1260. term.c.attr.bg = defaultbg;
  1261. break;
  1262. default:
  1263. if (BETWEEN(attr[i], 30, 37)) {
  1264. term.c.attr.fg = attr[i] - 30;
  1265. } else if (BETWEEN(attr[i], 40, 47)) {
  1266. term.c.attr.bg = attr[i] - 40;
  1267. } else if (BETWEEN(attr[i], 90, 97)) {
  1268. term.c.attr.fg = attr[i] - 90 + 8;
  1269. } else if (BETWEEN(attr[i], 100, 107)) {
  1270. term.c.attr.bg = attr[i] - 100 + 8;
  1271. } else {
  1272. fprintf(stderr,
  1273. "erresc(default): gfx attr %d unknown\n",
  1274. attr[i]);
  1275. csidump();
  1276. }
  1277. break;
  1278. }
  1279. }
  1280. }
  1281. void
  1282. tsetscroll(int t, int b)
  1283. {
  1284. int temp;
  1285. LIMIT(t, 0, term.row-1);
  1286. LIMIT(b, 0, term.row-1);
  1287. if (t > b) {
  1288. temp = t;
  1289. t = b;
  1290. b = temp;
  1291. }
  1292. term.top = t;
  1293. term.bot = b;
  1294. }
  1295. void
  1296. tsetmode(int priv, int set, int *args, int narg)
  1297. {
  1298. int alt, *lim;
  1299. for (lim = args + narg; args < lim; ++args) {
  1300. if (priv) {
  1301. switch (*args) {
  1302. case 1: /* DECCKM -- Cursor key */
  1303. xsetmode(set, MODE_APPCURSOR);
  1304. break;
  1305. case 5: /* DECSCNM -- Reverse video */
  1306. xsetmode(set, MODE_REVERSE);
  1307. break;
  1308. case 6: /* DECOM -- Origin */
  1309. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1310. tmoveato(0, 0);
  1311. break;
  1312. case 7: /* DECAWM -- Auto wrap */
  1313. MODBIT(term.mode, set, MODE_WRAP);
  1314. break;
  1315. case 0: /* Error (IGNORED) */
  1316. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1317. case 3: /* DECCOLM -- Column (IGNORED) */
  1318. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1319. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1320. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1321. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1322. case 42: /* DECNRCM -- National characters (IGNORED) */
  1323. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1324. break;
  1325. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1326. xsetmode(!set, MODE_HIDE);
  1327. break;
  1328. case 9: /* X10 mouse compatibility mode */
  1329. xsetpointermotion(0);
  1330. xsetmode(0, MODE_MOUSE);
  1331. xsetmode(set, MODE_MOUSEX10);
  1332. break;
  1333. case 1000: /* 1000: report button press */
  1334. xsetpointermotion(0);
  1335. xsetmode(0, MODE_MOUSE);
  1336. xsetmode(set, MODE_MOUSEBTN);
  1337. break;
  1338. case 1002: /* 1002: report motion on button press */
  1339. xsetpointermotion(0);
  1340. xsetmode(0, MODE_MOUSE);
  1341. xsetmode(set, MODE_MOUSEMOTION);
  1342. break;
  1343. case 1003: /* 1003: enable all mouse motions */
  1344. xsetpointermotion(set);
  1345. xsetmode(0, MODE_MOUSE);
  1346. xsetmode(set, MODE_MOUSEMANY);
  1347. break;
  1348. case 1004: /* 1004: send focus events to tty */
  1349. xsetmode(set, MODE_FOCUS);
  1350. break;
  1351. case 1006: /* 1006: extended reporting mode */
  1352. xsetmode(set, MODE_MOUSESGR);
  1353. break;
  1354. case 1034:
  1355. xsetmode(set, MODE_8BIT);
  1356. break;
  1357. case 1049: /* swap screen & set/restore cursor as xterm */
  1358. if (!allowaltscreen)
  1359. break;
  1360. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1361. /* FALLTHROUGH */
  1362. case 47: /* swap screen */
  1363. case 1047:
  1364. if (!allowaltscreen)
  1365. break;
  1366. alt = IS_SET(MODE_ALTSCREEN);
  1367. if (alt) {
  1368. tclearregion(0, 0, term.col-1,
  1369. term.row-1);
  1370. }
  1371. if (set ^ alt) /* set is always 1 or 0 */
  1372. tswapscreen();
  1373. if (*args != 1049)
  1374. break;
  1375. /* FALLTHROUGH */
  1376. case 1048:
  1377. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1378. break;
  1379. case 2004: /* 2004: bracketed paste mode */
  1380. xsetmode(set, MODE_BRCKTPASTE);
  1381. break;
  1382. /* Not implemented mouse modes. See comments there. */
  1383. case 1001: /* mouse highlight mode; can hang the
  1384. terminal by design when implemented. */
  1385. case 1005: /* UTF-8 mouse mode; will confuse
  1386. applications not supporting UTF-8
  1387. and luit. */
  1388. case 1015: /* urxvt mangled mouse mode; incompatible
  1389. and can be mistaken for other control
  1390. codes. */
  1391. break;
  1392. default:
  1393. fprintf(stderr,
  1394. "erresc: unknown private set/reset mode %d\n",
  1395. *args);
  1396. break;
  1397. }
  1398. } else {
  1399. switch (*args) {
  1400. case 0: /* Error (IGNORED) */
  1401. break;
  1402. case 2:
  1403. xsetmode(set, MODE_KBDLOCK);
  1404. break;
  1405. case 4: /* IRM -- Insertion-replacement */
  1406. MODBIT(term.mode, set, MODE_INSERT);
  1407. break;
  1408. case 12: /* SRM -- Send/Receive */
  1409. MODBIT(term.mode, !set, MODE_ECHO);
  1410. break;
  1411. case 20: /* LNM -- Linefeed/new line */
  1412. MODBIT(term.mode, set, MODE_CRLF);
  1413. break;
  1414. default:
  1415. fprintf(stderr,
  1416. "erresc: unknown set/reset mode %d\n",
  1417. *args);
  1418. break;
  1419. }
  1420. }
  1421. }
  1422. }
  1423. void
  1424. csihandle(void)
  1425. {
  1426. char buf[40];
  1427. int len;
  1428. switch (csiescseq.mode[0]) {
  1429. default:
  1430. unknown:
  1431. fprintf(stderr, "erresc: unknown csi ");
  1432. csidump();
  1433. /* die(""); */
  1434. break;
  1435. case '@': /* ICH -- Insert <n> blank char */
  1436. DEFAULT(csiescseq.arg[0], 1);
  1437. tinsertblank(csiescseq.arg[0]);
  1438. break;
  1439. case 'A': /* CUU -- Cursor <n> Up */
  1440. DEFAULT(csiescseq.arg[0], 1);
  1441. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1442. break;
  1443. case 'B': /* CUD -- Cursor <n> Down */
  1444. case 'e': /* VPR --Cursor <n> Down */
  1445. DEFAULT(csiescseq.arg[0], 1);
  1446. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1447. break;
  1448. case 'i': /* MC -- Media Copy */
  1449. switch (csiescseq.arg[0]) {
  1450. case 0:
  1451. tdump();
  1452. break;
  1453. case 1:
  1454. tdumpline(term.c.y);
  1455. break;
  1456. case 2:
  1457. tdumpsel();
  1458. break;
  1459. case 4:
  1460. term.mode &= ~MODE_PRINT;
  1461. break;
  1462. case 5:
  1463. term.mode |= MODE_PRINT;
  1464. break;
  1465. }
  1466. break;
  1467. case 'c': /* DA -- Device Attributes */
  1468. if (csiescseq.arg[0] == 0)
  1469. ttywrite(vtiden, strlen(vtiden), 0);
  1470. break;
  1471. case 'b': /* REP -- if last char is printable print it <n> more times */
  1472. DEFAULT(csiescseq.arg[0], 1);
  1473. if (term.lastc)
  1474. while (csiescseq.arg[0]-- > 0)
  1475. tputc(term.lastc);
  1476. break;
  1477. case 'C': /* CUF -- Cursor <n> Forward */
  1478. case 'a': /* HPR -- Cursor <n> Forward */
  1479. DEFAULT(csiescseq.arg[0], 1);
  1480. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1481. break;
  1482. case 'D': /* CUB -- Cursor <n> Backward */
  1483. DEFAULT(csiescseq.arg[0], 1);
  1484. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1485. break;
  1486. case 'E': /* CNL -- Cursor <n> Down and first col */
  1487. DEFAULT(csiescseq.arg[0], 1);
  1488. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1489. break;
  1490. case 'F': /* CPL -- Cursor <n> Up and first col */
  1491. DEFAULT(csiescseq.arg[0], 1);
  1492. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1493. break;
  1494. case 'g': /* TBC -- Tabulation clear */
  1495. switch (csiescseq.arg[0]) {
  1496. case 0: /* clear current tab stop */
  1497. term.tabs[term.c.x] = 0;
  1498. break;
  1499. case 3: /* clear all the tabs */
  1500. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1501. break;
  1502. default:
  1503. goto unknown;
  1504. }
  1505. break;
  1506. case 'G': /* CHA -- Move to <col> */
  1507. case '`': /* HPA */
  1508. DEFAULT(csiescseq.arg[0], 1);
  1509. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1510. break;
  1511. case 'H': /* CUP -- Move to <row> <col> */
  1512. case 'f': /* HVP */
  1513. DEFAULT(csiescseq.arg[0], 1);
  1514. DEFAULT(csiescseq.arg[1], 1);
  1515. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1516. break;
  1517. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1518. DEFAULT(csiescseq.arg[0], 1);
  1519. tputtab(csiescseq.arg[0]);
  1520. break;
  1521. case 'J': /* ED -- Clear screen */
  1522. switch (csiescseq.arg[0]) {
  1523. case 0: /* below */
  1524. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1525. if (term.c.y < term.row-1) {
  1526. tclearregion(0, term.c.y+1, term.col-1,
  1527. term.row-1);
  1528. }
  1529. break;
  1530. case 1: /* above */
  1531. if (term.c.y > 1)
  1532. tclearregion(0, 0, term.col-1, term.c.y-1);
  1533. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1534. break;
  1535. case 2: /* all */
  1536. tclearregion(0, 0, term.col-1, term.row-1);
  1537. break;
  1538. default:
  1539. goto unknown;
  1540. }
  1541. break;
  1542. case 'K': /* EL -- Clear line */
  1543. switch (csiescseq.arg[0]) {
  1544. case 0: /* right */
  1545. tclearregion(term.c.x, term.c.y, term.col-1,
  1546. term.c.y);
  1547. break;
  1548. case 1: /* left */
  1549. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1550. break;
  1551. case 2: /* all */
  1552. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1553. break;
  1554. }
  1555. break;
  1556. case 'S': /* SU -- Scroll <n> line up */
  1557. DEFAULT(csiescseq.arg[0], 1);
  1558. tscrollup(term.top, csiescseq.arg[0]);
  1559. break;
  1560. case 'T': /* SD -- Scroll <n> line down */
  1561. DEFAULT(csiescseq.arg[0], 1);
  1562. tscrolldown(term.top, csiescseq.arg[0]);
  1563. break;
  1564. case 'L': /* IL -- Insert <n> blank lines */
  1565. DEFAULT(csiescseq.arg[0], 1);
  1566. tinsertblankline(csiescseq.arg[0]);
  1567. break;
  1568. case 'l': /* RM -- Reset Mode */
  1569. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1570. break;
  1571. case 'M': /* DL -- Delete <n> lines */
  1572. DEFAULT(csiescseq.arg[0], 1);
  1573. tdeleteline(csiescseq.arg[0]);
  1574. break;
  1575. case 'X': /* ECH -- Erase <n> char */
  1576. DEFAULT(csiescseq.arg[0], 1);
  1577. tclearregion(term.c.x, term.c.y,
  1578. term.c.x + csiescseq.arg[0] - 1, term.c.y);
  1579. break;
  1580. case 'P': /* DCH -- Delete <n> char */
  1581. DEFAULT(csiescseq.arg[0], 1);
  1582. tdeletechar(csiescseq.arg[0]);
  1583. break;
  1584. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1585. DEFAULT(csiescseq.arg[0], 1);
  1586. tputtab(-csiescseq.arg[0]);
  1587. break;
  1588. case 'd': /* VPA -- Move to <row> */
  1589. DEFAULT(csiescseq.arg[0], 1);
  1590. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1591. break;
  1592. case 'h': /* SM -- Set terminal mode */
  1593. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1594. break;
  1595. case 'm': /* SGR -- Terminal attribute (color) */
  1596. tsetattr(csiescseq.arg, csiescseq.narg);
  1597. break;
  1598. case 'n': /* DSR – Device Status Report (cursor position) */
  1599. if (csiescseq.arg[0] == 6) {
  1600. len = snprintf(buf, sizeof(buf), "\033[%i;%iR",
  1601. term.c.y+1, term.c.x+1);
  1602. ttywrite(buf, len, 0);
  1603. }
  1604. break;
  1605. case 'r': /* DECSTBM -- Set Scrolling Region */
  1606. if (csiescseq.priv) {
  1607. goto unknown;
  1608. } else {
  1609. DEFAULT(csiescseq.arg[0], 1);
  1610. DEFAULT(csiescseq.arg[1], term.row);
  1611. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1612. tmoveato(0, 0);
  1613. }
  1614. break;
  1615. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1616. tcursor(CURSOR_SAVE);
  1617. break;
  1618. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1619. tcursor(CURSOR_LOAD);
  1620. break;
  1621. case ' ':
  1622. switch (csiescseq.mode[1]) {
  1623. case 'q': /* DECSCUSR -- Set Cursor Style */
  1624. if (xsetcursor(csiescseq.arg[0]))
  1625. goto unknown;
  1626. break;
  1627. default:
  1628. goto unknown;
  1629. }
  1630. break;
  1631. }
  1632. }
  1633. void
  1634. csidump(void)
  1635. {
  1636. size_t i;
  1637. uint c;
  1638. fprintf(stderr, "ESC[");
  1639. for (i = 0; i < csiescseq.len; i++) {
  1640. c = csiescseq.buf[i] & 0xff;
  1641. if (isprint(c)) {
  1642. putc(c, stderr);
  1643. } else if (c == '\n') {
  1644. fprintf(stderr, "(\\n)");
  1645. } else if (c == '\r') {
  1646. fprintf(stderr, "(\\r)");
  1647. } else if (c == 0x1b) {
  1648. fprintf(stderr, "(\\e)");
  1649. } else {
  1650. fprintf(stderr, "(%02x)", c);
  1651. }
  1652. }
  1653. putc('\n', stderr);
  1654. }
  1655. void
  1656. csireset(void)
  1657. {
  1658. memset(&csiescseq, 0, sizeof(csiescseq));
  1659. }
  1660. void
  1661. strhandle(void)
  1662. {
  1663. char *p = NULL, *dec;
  1664. int j, narg, par;
  1665. term.esc &= ~(ESC_STR_END|ESC_STR);
  1666. strparse();
  1667. par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
  1668. switch (strescseq.type) {
  1669. case ']': /* OSC -- Operating System Command */
  1670. switch (par) {
  1671. case 0:
  1672. if (narg > 1) {
  1673. xsettitle(strescseq.args[1]);
  1674. xseticontitle(strescseq.args[1]);
  1675. }
  1676. return;
  1677. case 1:
  1678. if (narg > 1)
  1679. xseticontitle(strescseq.args[1]);
  1680. return;
  1681. case 2:
  1682. if (narg > 1)
  1683. xsettitle(strescseq.args[1]);
  1684. return;
  1685. case 52:
  1686. if (narg > 2 && allowwindowops) {
  1687. dec = base64dec(strescseq.args[2]);
  1688. if (dec) {
  1689. xsetsel(dec);
  1690. xclipcopy();
  1691. } else {
  1692. fprintf(stderr, "erresc: invalid base64\n");
  1693. }
  1694. }
  1695. return;
  1696. case 4: /* color set */
  1697. if (narg < 3)
  1698. break;
  1699. p = strescseq.args[2];
  1700. /* FALLTHROUGH */
  1701. case 104: /* color reset, here p = NULL */
  1702. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  1703. if (xsetcolorname(j, p)) {
  1704. if (par == 104 && narg <= 1)
  1705. return; /* color reset without parameter */
  1706. fprintf(stderr, "erresc: invalid color j=%d, p=%s\n",
  1707. j, p ? p : "(null)");
  1708. } else {
  1709. /*
  1710. * TODO if defaultbg color is changed, borders
  1711. * are dirty
  1712. */
  1713. redraw();
  1714. }
  1715. return;
  1716. }
  1717. break;
  1718. case 'k': /* old title set compatibility */
  1719. xsettitle(strescseq.args[0]);
  1720. return;
  1721. case 'P': /* DCS -- Device Control String */
  1722. case '_': /* APC -- Application Program Command */
  1723. case '^': /* PM -- Privacy Message */
  1724. return;
  1725. }
  1726. fprintf(stderr, "erresc: unknown str ");
  1727. strdump();
  1728. }
  1729. void
  1730. strparse(void)
  1731. {
  1732. int c;
  1733. char *p = strescseq.buf;
  1734. strescseq.narg = 0;
  1735. strescseq.buf[strescseq.len] = '\0';
  1736. if (*p == '\0')
  1737. return;
  1738. while (strescseq.narg < STR_ARG_SIZ) {
  1739. strescseq.args[strescseq.narg++] = p;
  1740. while ((c = *p) != ';' && c != '\0')
  1741. ++p;
  1742. if (c == '\0')
  1743. return;
  1744. *p++ = '\0';
  1745. }
  1746. }
  1747. void
  1748. externalpipe(const Arg *arg)
  1749. {
  1750. int to[2];
  1751. char buf[UTF_SIZ];
  1752. void (*oldsigpipe)(int);
  1753. Glyph *bp, *end;
  1754. int lastpos, n, newline;
  1755. if (pipe(to) == -1)
  1756. return;
  1757. switch (fork()) {
  1758. case -1:
  1759. close(to[0]);
  1760. close(to[1]);
  1761. return;
  1762. case 0:
  1763. dup2(to[0], STDIN_FILENO);
  1764. close(to[0]);
  1765. close(to[1]);
  1766. execvp(((char **)arg->v)[0], (char **)arg->v);
  1767. fprintf(stderr, "st: execvp %s\n", ((char **)arg->v)[0]);
  1768. perror("failed");
  1769. exit(0);
  1770. }
  1771. close(to[0]);
  1772. /* ignore sigpipe for now, in case child exists early */
  1773. oldsigpipe = signal(SIGPIPE, SIG_IGN);
  1774. newline = 0;
  1775. for (n = 0; n < term.row; n++) {
  1776. bp = term.line[n];
  1777. lastpos = MIN(tlinelen(n) + 1, term.col) - 1;
  1778. if (lastpos < 0)
  1779. break;
  1780. end = &bp[lastpos + 1];
  1781. for (; bp < end; ++bp)
  1782. if (xwrite(to[1], buf, utf8encode(bp->u, buf)) < 0)
  1783. break;
  1784. if ((newline = term.line[n][lastpos].mode & ATTR_WRAP))
  1785. continue;
  1786. if (xwrite(to[1], "\n", 1) < 0)
  1787. break;
  1788. newline = 0;
  1789. }
  1790. if (newline)
  1791. (void)xwrite(to[1], "\n", 1);
  1792. close(to[1]);
  1793. /* restore */
  1794. signal(SIGPIPE, oldsigpipe);
  1795. }
  1796. void
  1797. strdump(void)
  1798. {
  1799. size_t i;
  1800. uint c;
  1801. fprintf(stderr, "ESC%c", strescseq.type);
  1802. for (i = 0; i < strescseq.len; i++) {
  1803. c = strescseq.buf[i] & 0xff;
  1804. if (c == '\0') {
  1805. putc('\n', stderr);
  1806. return;
  1807. } else if (isprint(c)) {
  1808. putc(c, stderr);
  1809. } else if (c == '\n') {
  1810. fprintf(stderr, "(\\n)");
  1811. } else if (c == '\r') {
  1812. fprintf(stderr, "(\\r)");
  1813. } else if (c == 0x1b) {
  1814. fprintf(stderr, "(\\e)");
  1815. } else {
  1816. fprintf(stderr, "(%02x)", c);
  1817. }
  1818. }
  1819. fprintf(stderr, "ESC\\\n");
  1820. }
  1821. void
  1822. strreset(void)
  1823. {
  1824. strescseq = (STREscape){
  1825. .buf = xrealloc(strescseq.buf, STR_BUF_SIZ),
  1826. .siz = STR_BUF_SIZ,
  1827. };
  1828. }
  1829. void
  1830. sendbreak(const Arg *arg)
  1831. {
  1832. if (tcsendbreak(cmdfd, 0))
  1833. perror("Error sending break");
  1834. }
  1835. void
  1836. tprinter(char *s, size_t len)
  1837. {
  1838. if (iofd != -1 && xwrite(iofd, s, len) < 0) {
  1839. perror("Error writing to output file");
  1840. close(iofd);
  1841. iofd = -1;
  1842. }
  1843. }
  1844. void
  1845. iso14755(const Arg *arg)
  1846. {
  1847. FILE *p;
  1848. char *us, *e, codepoint[9], uc[UTF_SIZ];
  1849. unsigned long utf32;
  1850. if (!(p = popen(iso14755_cmd, "r")))
  1851. return;
  1852. us = fgets(codepoint, sizeof(codepoint), p);
  1853. pclose(p);
  1854. if (!us || *us == '\0' || *us == '-' || strlen(us) > 7)
  1855. return;
  1856. if ((utf32 = strtoul(us, &e, 16)) == ULONG_MAX ||
  1857. (*e != '\n' && *e != '\0'))
  1858. return;
  1859. ttywrite(uc, utf8encode(utf32, uc), 1);
  1860. }
  1861. void
  1862. toggleprinter(const Arg *arg)
  1863. {
  1864. term.mode ^= MODE_PRINT;
  1865. }
  1866. void
  1867. printscreen(const Arg *arg)
  1868. {
  1869. tdump();
  1870. }
  1871. void
  1872. printsel(const Arg *arg)
  1873. {
  1874. tdumpsel();
  1875. }
  1876. void
  1877. tdumpsel(void)
  1878. {
  1879. char *ptr;
  1880. if ((ptr = getsel())) {
  1881. tprinter(ptr, strlen(ptr));
  1882. free(ptr);
  1883. }
  1884. }
  1885. void
  1886. tdumpline(int n)
  1887. {
  1888. char buf[UTF_SIZ];
  1889. Glyph *bp, *end;
  1890. bp = &term.line[n][0];
  1891. end = &bp[MIN(tlinelen(n), term.col) - 1];
  1892. if (bp != end || bp->u != ' ') {
  1893. for ( ; bp <= end; ++bp)
  1894. tprinter(buf, utf8encode(bp->u, buf));
  1895. }
  1896. tprinter("\n", 1);
  1897. }
  1898. void
  1899. tdump(void)
  1900. {
  1901. int i;
  1902. for (i = 0; i < term.row; ++i)
  1903. tdumpline(i);
  1904. }
  1905. void
  1906. tputtab(int n)
  1907. {
  1908. uint x = term.c.x;
  1909. if (n > 0) {
  1910. while (x < term.col && n--)
  1911. for (++x; x < term.col && !term.tabs[x]; ++x)
  1912. /* nothing */ ;
  1913. } else if (n < 0) {
  1914. while (x > 0 && n++)
  1915. for (--x; x > 0 && !term.tabs[x]; --x)
  1916. /* nothing */ ;
  1917. }
  1918. term.c.x = LIMIT(x, 0, term.col-1);
  1919. }
  1920. void
  1921. tdefutf8(char ascii)
  1922. {
  1923. if (ascii == 'G')
  1924. term.mode |= MODE_UTF8;
  1925. else if (ascii == '@')
  1926. term.mode &= ~MODE_UTF8;
  1927. }
  1928. void
  1929. tdeftran(char ascii)
  1930. {
  1931. static char cs[] = "0B";
  1932. static int vcs[] = {CS_GRAPHIC0, CS_USA};
  1933. char *p;
  1934. if ((p = strchr(cs, ascii)) == NULL) {
  1935. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1936. } else {
  1937. term.trantbl[term.icharset] = vcs[p - cs];
  1938. }
  1939. }
  1940. void
  1941. tdectest(char c)
  1942. {
  1943. int x, y;
  1944. if (c == '8') { /* DEC screen alignment test. */
  1945. for (x = 0; x < term.col; ++x) {
  1946. for (y = 0; y < term.row; ++y)
  1947. tsetchar('E', &term.c.attr, x, y);
  1948. }
  1949. }
  1950. }
  1951. void
  1952. tstrsequence(uchar c)
  1953. {
  1954. switch (c) {
  1955. case 0x90: /* DCS -- Device Control String */
  1956. c = 'P';
  1957. break;
  1958. case 0x9f: /* APC -- Application Program Command */
  1959. c = '_';
  1960. break;
  1961. case 0x9e: /* PM -- Privacy Message */
  1962. c = '^';
  1963. break;
  1964. case 0x9d: /* OSC -- Operating System Command */
  1965. c = ']';
  1966. break;
  1967. }
  1968. strreset();
  1969. strescseq.type = c;
  1970. term.esc |= ESC_STR;
  1971. }
  1972. void
  1973. tcontrolcode(uchar ascii)
  1974. {
  1975. switch (ascii) {
  1976. case '\t': /* HT */
  1977. tputtab(1);
  1978. return;
  1979. case '\b': /* BS */
  1980. tmoveto(term.c.x-1, term.c.y);
  1981. return;
  1982. case '\r': /* CR */
  1983. tmoveto(0, term.c.y);
  1984. return;
  1985. case '\f': /* LF */
  1986. case '\v': /* VT */
  1987. case '\n': /* LF */
  1988. /* go to first col if the mode is set */
  1989. tnewline(IS_SET(MODE_CRLF));
  1990. return;
  1991. case '\a': /* BEL */
  1992. if (term.esc & ESC_STR_END) {
  1993. /* backwards compatibility to xterm */
  1994. strhandle();
  1995. } else {
  1996. xbell();
  1997. }
  1998. break;
  1999. case '\033': /* ESC */
  2000. csireset();
  2001. term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
  2002. term.esc |= ESC_START;
  2003. return;
  2004. case '\016': /* SO (LS1 -- Locking shift 1) */
  2005. case '\017': /* SI (LS0 -- Locking shift 0) */
  2006. term.charset = 1 - (ascii - '\016');
  2007. return;
  2008. case '\032': /* SUB */
  2009. tsetchar('?', &term.c.attr, term.c.x, term.c.y);
  2010. /* FALLTHROUGH */
  2011. case '\030': /* CAN */
  2012. csireset();
  2013. break;
  2014. case '\005': /* ENQ (IGNORED) */
  2015. case '\000': /* NUL (IGNORED) */
  2016. case '\021': /* XON (IGNORED) */
  2017. case '\023': /* XOFF (IGNORED) */
  2018. case 0177: /* DEL (IGNORED) */
  2019. return;
  2020. case 0x80: /* TODO: PAD */
  2021. case 0x81: /* TODO: HOP */
  2022. case 0x82: /* TODO: BPH */
  2023. case 0x83: /* TODO: NBH */
  2024. case 0x84: /* TODO: IND */
  2025. break;
  2026. case 0x85: /* NEL -- Next line */
  2027. tnewline(1); /* always go to first col */
  2028. break;
  2029. case 0x86: /* TODO: SSA */
  2030. case 0x87: /* TODO: ESA */
  2031. break;
  2032. case 0x88: /* HTS -- Horizontal tab stop */
  2033. term.tabs[term.c.x] = 1;
  2034. break;
  2035. case 0x89: /* TODO: HTJ */
  2036. case 0x8a: /* TODO: VTS */
  2037. case 0x8b: /* TODO: PLD */
  2038. case 0x8c: /* TODO: PLU */
  2039. case 0x8d: /* TODO: RI */
  2040. case 0x8e: /* TODO: SS2 */
  2041. case 0x8f: /* TODO: SS3 */
  2042. case 0x91: /* TODO: PU1 */
  2043. case 0x92: /* TODO: PU2 */
  2044. case 0x93: /* TODO: STS */
  2045. case 0x94: /* TODO: CCH */
  2046. case 0x95: /* TODO: MW */
  2047. case 0x96: /* TODO: SPA */
  2048. case 0x97: /* TODO: EPA */
  2049. case 0x98: /* TODO: SOS */
  2050. case 0x99: /* TODO: SGCI */
  2051. break;
  2052. case 0x9a: /* DECID -- Identify Terminal */
  2053. ttywrite(vtiden, strlen(vtiden), 0);
  2054. break;
  2055. case 0x9b: /* TODO: CSI */
  2056. case 0x9c: /* TODO: ST */
  2057. break;
  2058. case 0x90: /* DCS -- Device Control String */
  2059. case 0x9d: /* OSC -- Operating System Command */
  2060. case 0x9e: /* PM -- Privacy Message */
  2061. case 0x9f: /* APC -- Application Program Command */
  2062. tstrsequence(ascii);
  2063. return;
  2064. }
  2065. /* only CAN, SUB, \a and C1 chars interrupt a sequence */
  2066. term.esc &= ~(ESC_STR_END|ESC_STR);
  2067. }
  2068. /*
  2069. * returns 1 when the sequence is finished and it hasn't to read
  2070. * more characters for this sequence, otherwise 0
  2071. */
  2072. int
  2073. eschandle(uchar ascii)
  2074. {
  2075. switch (ascii) {
  2076. case '[':
  2077. term.esc |= ESC_CSI;
  2078. return 0;
  2079. case '#':
  2080. term.esc |= ESC_TEST;
  2081. return 0;
  2082. case '%':
  2083. term.esc |= ESC_UTF8;
  2084. return 0;
  2085. case 'P': /* DCS -- Device Control String */
  2086. case '_': /* APC -- Application Program Command */
  2087. case '^': /* PM -- Privacy Message */
  2088. case ']': /* OSC -- Operating System Command */
  2089. case 'k': /* old title set compatibility */
  2090. tstrsequence(ascii);
  2091. return 0;
  2092. case 'n': /* LS2 -- Locking shift 2 */
  2093. case 'o': /* LS3 -- Locking shift 3 */
  2094. term.charset = 2 + (ascii - 'n');
  2095. break;
  2096. case '(': /* GZD4 -- set primary charset G0 */
  2097. case ')': /* G1D4 -- set secondary charset G1 */
  2098. case '*': /* G2D4 -- set tertiary charset G2 */
  2099. case '+': /* G3D4 -- set quaternary charset G3 */
  2100. term.icharset = ascii - '(';
  2101. term.esc |= ESC_ALTCHARSET;
  2102. return 0;
  2103. case 'D': /* IND -- Linefeed */
  2104. if (term.c.y == term.bot) {
  2105. tscrollup(term.top, 1);
  2106. } else {
  2107. tmoveto(term.c.x, term.c.y+1);
  2108. }
  2109. break;
  2110. case 'E': /* NEL -- Next line */
  2111. tnewline(1); /* always go to first col */
  2112. break;
  2113. case 'H': /* HTS -- Horizontal tab stop */
  2114. term.tabs[term.c.x] = 1;
  2115. break;
  2116. case 'M': /* RI -- Reverse index */
  2117. if (term.c.y == term.top) {
  2118. tscrolldown(term.top, 1);
  2119. } else {
  2120. tmoveto(term.c.x, term.c.y-1);
  2121. }
  2122. break;
  2123. case 'Z': /* DECID -- Identify Terminal */
  2124. ttywrite(vtiden, strlen(vtiden), 0);
  2125. break;
  2126. case 'c': /* RIS -- Reset to initial state */
  2127. treset();
  2128. resettitle();
  2129. xloadcols();
  2130. break;
  2131. case '=': /* DECPAM -- Application keypad */
  2132. xsetmode(1, MODE_APPKEYPAD);
  2133. break;
  2134. case '>': /* DECPNM -- Normal keypad */
  2135. xsetmode(0, MODE_APPKEYPAD);
  2136. break;
  2137. case '7': /* DECSC -- Save Cursor */
  2138. tcursor(CURSOR_SAVE);
  2139. break;
  2140. case '8': /* DECRC -- Restore Cursor */
  2141. tcursor(CURSOR_LOAD);
  2142. break;
  2143. case '\\': /* ST -- String Terminator */
  2144. if (term.esc & ESC_STR_END)
  2145. strhandle();
  2146. break;
  2147. default:
  2148. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2149. (uchar) ascii, isprint(ascii)? ascii:'.');
  2150. break;
  2151. }
  2152. return 1;
  2153. }
  2154. void
  2155. tputc(Rune u)
  2156. {
  2157. char c[UTF_SIZ];
  2158. int control;
  2159. int width, len;
  2160. Glyph *gp;
  2161. control = ISCONTROL(u);
  2162. if (u < 127 || !IS_SET(MODE_UTF8)) {
  2163. c[0] = u;
  2164. width = len = 1;
  2165. } else {
  2166. len = utf8encode(u, c);
  2167. if (!control && (width = wcwidth(u)) == -1)
  2168. width = 1;
  2169. }
  2170. if (IS_SET(MODE_PRINT))
  2171. tprinter(c, len);
  2172. /*
  2173. * STR sequence must be checked before anything else
  2174. * because it uses all following characters until it
  2175. * receives a ESC, a SUB, a ST or any other C1 control
  2176. * character.
  2177. */
  2178. if (term.esc & ESC_STR) {
  2179. if (u == '\a' || u == 030 || u == 032 || u == 033 ||
  2180. ISCONTROLC1(u)) {
  2181. term.esc &= ~(ESC_START|ESC_STR);
  2182. term.esc |= ESC_STR_END;
  2183. goto check_control_code;
  2184. }
  2185. if (strescseq.len+len >= strescseq.siz) {
  2186. /*
  2187. * Here is a bug in terminals. If the user never sends
  2188. * some code to stop the str or esc command, then st
  2189. * will stop responding. But this is better than
  2190. * silently failing with unknown characters. At least
  2191. * then users will report back.
  2192. *
  2193. * In the case users ever get fixed, here is the code:
  2194. */
  2195. /*
  2196. * term.esc = 0;
  2197. * strhandle();
  2198. */
  2199. if (strescseq.siz > (SIZE_MAX - UTF_SIZ) / 2)
  2200. return;
  2201. strescseq.siz *= 2;
  2202. strescseq.buf = xrealloc(strescseq.buf, strescseq.siz);
  2203. }
  2204. memmove(&strescseq.buf[strescseq.len], c, len);
  2205. strescseq.len += len;
  2206. return;
  2207. }
  2208. check_control_code:
  2209. /*
  2210. * Actions of control codes must be performed as soon they arrive
  2211. * because they can be embedded inside a control sequence, and
  2212. * they must not cause conflicts with sequences.
  2213. */
  2214. if (control) {
  2215. tcontrolcode(u);
  2216. /*
  2217. * control codes are not shown ever
  2218. */
  2219. if (!term.esc)
  2220. term.lastc = 0;
  2221. return;
  2222. } else if (term.esc & ESC_START) {
  2223. if (term.esc & ESC_CSI) {
  2224. csiescseq.buf[csiescseq.len++] = u;
  2225. if (BETWEEN(u, 0x40, 0x7E)
  2226. || csiescseq.len >= \
  2227. sizeof(csiescseq.buf)-1) {
  2228. term.esc = 0;
  2229. csiparse();
  2230. csihandle();
  2231. }
  2232. return;
  2233. } else if (term.esc & ESC_UTF8) {
  2234. tdefutf8(u);
  2235. } else if (term.esc & ESC_ALTCHARSET) {
  2236. tdeftran(u);
  2237. } else if (term.esc & ESC_TEST) {
  2238. tdectest(u);
  2239. } else {
  2240. if (!eschandle(u))
  2241. return;
  2242. /* sequence already finished */
  2243. }
  2244. term.esc = 0;
  2245. /*
  2246. * All characters which form part of a sequence are not
  2247. * printed
  2248. */
  2249. return;
  2250. }
  2251. if (selected(term.c.x, term.c.y))
  2252. selclear();
  2253. gp = &term.line[term.c.y][term.c.x];
  2254. if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2255. gp->mode |= ATTR_WRAP;
  2256. tnewline(1);
  2257. gp = &term.line[term.c.y][term.c.x];
  2258. }
  2259. if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
  2260. memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
  2261. if (term.c.x+width > term.col) {
  2262. tnewline(1);
  2263. gp = &term.line[term.c.y][term.c.x];
  2264. }
  2265. tsetchar(u, &term.c.attr, term.c.x, term.c.y);
  2266. term.lastc = u;
  2267. if (width == 2) {
  2268. gp->mode |= ATTR_WIDE;
  2269. if (term.c.x+1 < term.col) {
  2270. gp[1].u = '\0';
  2271. gp[1].mode = ATTR_WDUMMY;
  2272. }
  2273. }
  2274. if (term.c.x+width < term.col) {
  2275. tmoveto(term.c.x+width, term.c.y);
  2276. } else {
  2277. term.c.state |= CURSOR_WRAPNEXT;
  2278. }
  2279. }
  2280. int
  2281. twrite(const char *buf, int buflen, int show_ctrl)
  2282. {
  2283. int charsize;
  2284. Rune u;
  2285. int n;
  2286. for (n = 0; n < buflen; n += charsize) {
  2287. if (IS_SET(MODE_UTF8)) {
  2288. /* process a complete utf8 char */
  2289. charsize = utf8decode(buf + n, &u, buflen - n);
  2290. if (charsize == 0)
  2291. break;
  2292. } else {
  2293. u = buf[n] & 0xFF;
  2294. charsize = 1;
  2295. }
  2296. if (show_ctrl && ISCONTROL(u)) {
  2297. if (u & 0x80) {
  2298. u &= 0x7f;
  2299. tputc('^');
  2300. tputc('[');
  2301. } else if (u != '\n' && u != '\r' && u != '\t') {
  2302. u ^= 0x40;
  2303. tputc('^');
  2304. }
  2305. }
  2306. tputc(u);
  2307. }
  2308. return n;
  2309. }
  2310. void
  2311. tresize(int col, int row)
  2312. {
  2313. int i;
  2314. int minrow = MIN(row, term.row);
  2315. int mincol = MIN(col, term.col);
  2316. int *bp;
  2317. TCursor c;
  2318. if (col < 1 || row < 1) {
  2319. fprintf(stderr,
  2320. "tresize: error resizing to %dx%d\n", col, row);
  2321. return;
  2322. }
  2323. /*
  2324. * slide screen to keep cursor where we expect it -
  2325. * tscrollup would work here, but we can optimize to
  2326. * memmove because we're freeing the earlier lines
  2327. */
  2328. for (i = 0; i <= term.c.y - row; i++) {
  2329. free(term.line[i]);
  2330. free(term.alt[i]);
  2331. }
  2332. /* ensure that both src and dst are not NULL */
  2333. if (i > 0) {
  2334. memmove(term.line, term.line + i, row * sizeof(Line));
  2335. memmove(term.alt, term.alt + i, row * sizeof(Line));
  2336. }
  2337. for (i += row; i < term.row; i++) {
  2338. free(term.line[i]);
  2339. free(term.alt[i]);
  2340. }
  2341. /* resize to new height */
  2342. term.line = xrealloc(term.line, row * sizeof(Line));
  2343. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2344. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2345. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2346. /* resize each row to new width, zero-pad if needed */
  2347. for (i = 0; i < minrow; i++) {
  2348. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2349. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2350. }
  2351. /* allocate any new rows */
  2352. for (/* i = minrow */; i < row; i++) {
  2353. term.line[i] = xmalloc(col * sizeof(Glyph));
  2354. term.alt[i] = xmalloc(col * sizeof(Glyph));
  2355. }
  2356. if (col > term.col) {
  2357. bp = term.tabs + term.col;
  2358. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2359. while (--bp > term.tabs && !*bp)
  2360. /* nothing */ ;
  2361. for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2362. *bp = 1;
  2363. }
  2364. /* update terminal size */
  2365. term.col = col;
  2366. term.row = row;
  2367. /* reset scrolling region */
  2368. tsetscroll(0, row-1);
  2369. /* make use of the LIMIT in tmoveto */
  2370. tmoveto(term.c.x, term.c.y);
  2371. /* Clearing both screens (it makes dirty all lines) */
  2372. c = term.c;
  2373. for (i = 0; i < 2; i++) {
  2374. if (mincol < col && 0 < minrow) {
  2375. tclearregion(mincol, 0, col - 1, minrow - 1);
  2376. }
  2377. if (0 < col && minrow < row) {
  2378. tclearregion(0, minrow, col - 1, row - 1);
  2379. }
  2380. tswapscreen();
  2381. tcursor(CURSOR_LOAD);
  2382. }
  2383. term.c = c;
  2384. }
  2385. void
  2386. resettitle(void)
  2387. {
  2388. xsettitle(NULL);
  2389. }
  2390. void
  2391. drawregion(int x1, int y1, int x2, int y2)
  2392. {
  2393. int y;
  2394. for (y = y1; y < y2; y++) {
  2395. if (!term.dirty[y])
  2396. continue;
  2397. term.dirty[y] = 0;
  2398. xdrawline(term.line[y], x1, y, x2);
  2399. }
  2400. }
  2401. void
  2402. draw(void)
  2403. {
  2404. int cx = term.c.x, ocx = term.ocx, ocy = term.ocy;
  2405. if (!xstartdraw())
  2406. return;
  2407. /* adjust cursor position */
  2408. LIMIT(term.ocx, 0, term.col-1);
  2409. LIMIT(term.ocy, 0, term.row-1);
  2410. if (term.line[term.ocy][term.ocx].mode & ATTR_WDUMMY)
  2411. term.ocx--;
  2412. if (term.line[term.c.y][cx].mode & ATTR_WDUMMY)
  2413. cx--;
  2414. drawregion(0, 0, term.col, term.row);
  2415. xdrawcursor(cx, term.c.y, term.line[term.c.y][cx],
  2416. term.ocx, term.ocy, term.line[term.ocy][term.ocx]);
  2417. term.ocx = cx;
  2418. term.ocy = term.c.y;
  2419. xfinishdraw();
  2420. if (ocx != term.ocx || ocy != term.ocy)
  2421. xximspot(term.ocx, term.ocy);
  2422. }
  2423. void
  2424. redraw(void)
  2425. {
  2426. tfulldirt();
  2427. draw();
  2428. }