Simple Terminal from SuckLess
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.

2597 lines
54 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
4 years ago
13 years ago
13 years ago
4 years ago
4 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
4 years ago
10 years ago
10 years ago
14 years ago
14 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. return;
  628. if (WIFEXITED(stat) && WEXITSTATUS(stat))
  629. die("child exited with status %d\n", WEXITSTATUS(stat));
  630. else if (WIFSIGNALED(stat))
  631. die("child terminated due to signal %d\n", WTERMSIG(stat));
  632. _exit(0);
  633. }
  634. void
  635. stty(char **args)
  636. {
  637. char cmd[_POSIX_ARG_MAX], **p, *q, *s;
  638. size_t n, siz;
  639. if ((n = strlen(stty_args)) > sizeof(cmd)-1)
  640. die("incorrect stty parameters\n");
  641. memcpy(cmd, stty_args, n);
  642. q = cmd + n;
  643. siz = sizeof(cmd) - n;
  644. for (p = args; p && (s = *p); ++p) {
  645. if ((n = strlen(s)) > siz-1)
  646. die("stty parameter length too long\n");
  647. *q++ = ' ';
  648. memcpy(q, s, n);
  649. q += n;
  650. siz -= n + 1;
  651. }
  652. *q = '\0';
  653. if (system(cmd) != 0)
  654. perror("Couldn't call stty");
  655. }
  656. int
  657. ttynew(char *line, char *cmd, char *out, char **args)
  658. {
  659. int m, s;
  660. if (out) {
  661. term.mode |= MODE_PRINT;
  662. iofd = (!strcmp(out, "-")) ?
  663. 1 : open(out, O_WRONLY | O_CREAT, 0666);
  664. if (iofd < 0) {
  665. fprintf(stderr, "Error opening %s:%s\n",
  666. out, strerror(errno));
  667. }
  668. }
  669. if (line) {
  670. if ((cmdfd = open(line, O_RDWR)) < 0)
  671. die("open line '%s' failed: %s\n",
  672. line, strerror(errno));
  673. dup2(cmdfd, 0);
  674. stty(args);
  675. return cmdfd;
  676. }
  677. /* seems to work fine on linux, openbsd and freebsd */
  678. if (openpty(&m, &s, NULL, NULL, NULL) < 0)
  679. die("openpty failed: %s\n", strerror(errno));
  680. switch (pid = fork()) {
  681. case -1:
  682. die("fork failed: %s\n", strerror(errno));
  683. break;
  684. case 0:
  685. close(iofd);
  686. setsid(); /* create a new process group */
  687. dup2(s, 0);
  688. dup2(s, 1);
  689. dup2(s, 2);
  690. if (ioctl(s, TIOCSCTTY, NULL) < 0)
  691. die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
  692. close(s);
  693. close(m);
  694. #ifdef __OpenBSD__
  695. if (pledge("stdio getpw proc exec", NULL) == -1)
  696. die("pledge\n");
  697. #endif
  698. execsh(cmd, args);
  699. break;
  700. default:
  701. #ifdef __OpenBSD__
  702. if (pledge("stdio rpath tty proc", NULL) == -1)
  703. die("pledge\n");
  704. #endif
  705. close(s);
  706. cmdfd = m;
  707. signal(SIGCHLD, sigchld);
  708. break;
  709. }
  710. return cmdfd;
  711. }
  712. size_t
  713. ttyread(void)
  714. {
  715. static char buf[BUFSIZ];
  716. static int buflen = 0;
  717. int ret, written;
  718. /* append read bytes to unprocessed bytes */
  719. ret = read(cmdfd, buf+buflen, LEN(buf)-buflen);
  720. switch (ret) {
  721. case 0:
  722. exit(0);
  723. case -1:
  724. die("couldn't read from shell: %s\n", strerror(errno));
  725. default:
  726. buflen += ret;
  727. written = twrite(buf, buflen, 0);
  728. buflen -= written;
  729. /* keep any incomplete UTF-8 byte sequence for the next call */
  730. if (buflen > 0)
  731. memmove(buf, buf + written, buflen);
  732. return ret;
  733. }
  734. }
  735. void
  736. ttywrite(const char *s, size_t n, int may_echo)
  737. {
  738. const char *next;
  739. if (may_echo && IS_SET(MODE_ECHO))
  740. twrite(s, n, 1);
  741. if (!IS_SET(MODE_CRLF)) {
  742. ttywriteraw(s, n);
  743. return;
  744. }
  745. /* This is similar to how the kernel handles ONLCR for ttys */
  746. while (n > 0) {
  747. if (*s == '\r') {
  748. next = s + 1;
  749. ttywriteraw("\r\n", 2);
  750. } else {
  751. next = memchr(s, '\r', n);
  752. DEFAULT(next, s + n);
  753. ttywriteraw(s, next - s);
  754. }
  755. n -= next - s;
  756. s = next;
  757. }
  758. }
  759. void
  760. ttywriteraw(const char *s, size_t n)
  761. {
  762. fd_set wfd, rfd;
  763. ssize_t r;
  764. size_t lim = 256;
  765. /*
  766. * Remember that we are using a pty, which might be a modem line.
  767. * Writing too much will clog the line. That's why we are doing this
  768. * dance.
  769. * FIXME: Migrate the world to Plan 9.
  770. */
  771. while (n > 0) {
  772. FD_ZERO(&wfd);
  773. FD_ZERO(&rfd);
  774. FD_SET(cmdfd, &wfd);
  775. FD_SET(cmdfd, &rfd);
  776. /* Check if we can write. */
  777. if (pselect(cmdfd+1, &rfd, &wfd, NULL, NULL, NULL) < 0) {
  778. if (errno == EINTR)
  779. continue;
  780. die("select failed: %s\n", strerror(errno));
  781. }
  782. if (FD_ISSET(cmdfd, &wfd)) {
  783. /*
  784. * Only write the bytes written by ttywrite() or the
  785. * default of 256. This seems to be a reasonable value
  786. * for a serial line. Bigger values might clog the I/O.
  787. */
  788. if ((r = write(cmdfd, s, (n < lim)? n : lim)) < 0)
  789. goto write_error;
  790. if (r < n) {
  791. /*
  792. * We weren't able to write out everything.
  793. * This means the buffer is getting full
  794. * again. Empty it.
  795. */
  796. if (n < lim)
  797. lim = ttyread();
  798. n -= r;
  799. s += r;
  800. } else {
  801. /* All bytes have been written. */
  802. break;
  803. }
  804. }
  805. if (FD_ISSET(cmdfd, &rfd))
  806. lim = ttyread();
  807. }
  808. return;
  809. write_error:
  810. die("write error on tty: %s\n", strerror(errno));
  811. }
  812. void
  813. ttyresize(int tw, int th)
  814. {
  815. struct winsize w;
  816. w.ws_row = term.row;
  817. w.ws_col = term.col;
  818. w.ws_xpixel = tw;
  819. w.ws_ypixel = th;
  820. if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  821. fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
  822. }
  823. void
  824. ttyhangup()
  825. {
  826. /* Send SIGHUP to shell */
  827. kill(pid, SIGHUP);
  828. }
  829. int
  830. tattrset(int attr)
  831. {
  832. int i, j;
  833. for (i = 0; i < term.row-1; i++) {
  834. for (j = 0; j < term.col-1; j++) {
  835. if (term.line[i][j].mode & attr)
  836. return 1;
  837. }
  838. }
  839. return 0;
  840. }
  841. void
  842. tsetdirt(int top, int bot)
  843. {
  844. int i;
  845. LIMIT(top, 0, term.row-1);
  846. LIMIT(bot, 0, term.row-1);
  847. for (i = top; i <= bot; i++)
  848. term.dirty[i] = 1;
  849. }
  850. void
  851. tsetdirtattr(int attr)
  852. {
  853. int i, j;
  854. for (i = 0; i < term.row-1; i++) {
  855. for (j = 0; j < term.col-1; j++) {
  856. if (term.line[i][j].mode & attr) {
  857. tsetdirt(i, i);
  858. break;
  859. }
  860. }
  861. }
  862. }
  863. void
  864. tfulldirt(void)
  865. {
  866. tsetdirt(0, term.row-1);
  867. }
  868. void
  869. tcursor(int mode)
  870. {
  871. static TCursor c[2];
  872. int alt = IS_SET(MODE_ALTSCREEN);
  873. if (mode == CURSOR_SAVE) {
  874. c[alt] = term.c;
  875. } else if (mode == CURSOR_LOAD) {
  876. term.c = c[alt];
  877. tmoveto(c[alt].x, c[alt].y);
  878. }
  879. }
  880. void
  881. treset(void)
  882. {
  883. uint i;
  884. term.c = (TCursor){{
  885. .mode = ATTR_NULL,
  886. .fg = defaultfg,
  887. .bg = defaultbg
  888. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  889. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  890. for (i = tabspaces; i < term.col; i += tabspaces)
  891. term.tabs[i] = 1;
  892. term.top = 0;
  893. term.bot = term.row - 1;
  894. term.mode = MODE_WRAP|MODE_UTF8;
  895. memset(term.trantbl, CS_USA, sizeof(term.trantbl));
  896. term.charset = 0;
  897. for (i = 0; i < 2; i++) {
  898. tmoveto(0, 0);
  899. tcursor(CURSOR_SAVE);
  900. tclearregion(0, 0, term.col-1, term.row-1);
  901. tswapscreen();
  902. }
  903. }
  904. void
  905. tnew(int col, int row)
  906. {
  907. term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
  908. tresize(col, row);
  909. treset();
  910. }
  911. void
  912. tswapscreen(void)
  913. {
  914. Line *tmp = term.line;
  915. term.line = term.alt;
  916. term.alt = tmp;
  917. term.mode ^= MODE_ALTSCREEN;
  918. tfulldirt();
  919. }
  920. void
  921. tscrolldown(int orig, int n)
  922. {
  923. int i;
  924. Line temp;
  925. LIMIT(n, 0, term.bot-orig+1);
  926. tsetdirt(orig, term.bot-n);
  927. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  928. for (i = term.bot; i >= orig+n; i--) {
  929. temp = term.line[i];
  930. term.line[i] = term.line[i-n];
  931. term.line[i-n] = temp;
  932. }
  933. selscroll(orig, n);
  934. }
  935. void
  936. tscrollup(int orig, int n)
  937. {
  938. int i;
  939. Line temp;
  940. LIMIT(n, 0, term.bot-orig+1);
  941. tclearregion(0, orig, term.col-1, orig+n-1);
  942. tsetdirt(orig+n, term.bot);
  943. for (i = orig; i <= term.bot-n; i++) {
  944. temp = term.line[i];
  945. term.line[i] = term.line[i+n];
  946. term.line[i+n] = temp;
  947. }
  948. selscroll(orig, -n);
  949. }
  950. void
  951. selscroll(int orig, int n)
  952. {
  953. if (sel.ob.x == -1)
  954. return;
  955. if (BETWEEN(sel.nb.y, orig, term.bot) != BETWEEN(sel.ne.y, orig, term.bot)) {
  956. selclear();
  957. } else if (BETWEEN(sel.nb.y, orig, term.bot)) {
  958. sel.ob.y += n;
  959. sel.oe.y += n;
  960. if (sel.ob.y < term.top || sel.ob.y > term.bot ||
  961. sel.oe.y < term.top || sel.oe.y > term.bot) {
  962. selclear();
  963. } else {
  964. selnormalize();
  965. }
  966. }
  967. }
  968. void
  969. tnewline(int first_col)
  970. {
  971. int y = term.c.y;
  972. if (y == term.bot) {
  973. tscrollup(term.top, 1);
  974. } else {
  975. y++;
  976. }
  977. tmoveto(first_col ? 0 : term.c.x, y);
  978. }
  979. void
  980. csiparse(void)
  981. {
  982. char *p = csiescseq.buf, *np;
  983. long int v;
  984. csiescseq.narg = 0;
  985. if (*p == '?') {
  986. csiescseq.priv = 1;
  987. p++;
  988. }
  989. csiescseq.buf[csiescseq.len] = '\0';
  990. while (p < csiescseq.buf+csiescseq.len) {
  991. np = NULL;
  992. v = strtol(p, &np, 10);
  993. if (np == p)
  994. v = 0;
  995. if (v == LONG_MAX || v == LONG_MIN)
  996. v = -1;
  997. csiescseq.arg[csiescseq.narg++] = v;
  998. p = np;
  999. if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
  1000. break;
  1001. p++;
  1002. }
  1003. csiescseq.mode[0] = *p++;
  1004. csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
  1005. }
  1006. /* for absolute user moves, when decom is set */
  1007. void
  1008. tmoveato(int x, int y)
  1009. {
  1010. tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
  1011. }
  1012. void
  1013. tmoveto(int x, int y)
  1014. {
  1015. int miny, maxy;
  1016. if (term.c.state & CURSOR_ORIGIN) {
  1017. miny = term.top;
  1018. maxy = term.bot;
  1019. } else {
  1020. miny = 0;
  1021. maxy = term.row - 1;
  1022. }
  1023. term.c.state &= ~CURSOR_WRAPNEXT;
  1024. term.c.x = LIMIT(x, 0, term.col-1);
  1025. term.c.y = LIMIT(y, miny, maxy);
  1026. }
  1027. void
  1028. tsetchar(Rune u, Glyph *attr, int x, int y)
  1029. {
  1030. static char *vt100_0[62] = { /* 0x41 - 0x7e */
  1031. "", "", "", "", "", "", "", /* A - G */
  1032. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  1033. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  1034. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  1035. "", "", "", "", "", "", "°", "±", /* ` - g */
  1036. "", "", "", "", "", "", "", "", /* h - o */
  1037. "", "", "", "", "", "", "", "", /* p - w */
  1038. "", "", "", "π", "", "£", "·", /* x - ~ */
  1039. };
  1040. /*
  1041. * The table is proudly stolen from rxvt.
  1042. */
  1043. if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
  1044. BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
  1045. utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
  1046. if (term.line[y][x].mode & ATTR_WIDE) {
  1047. if (x+1 < term.col) {
  1048. term.line[y][x+1].u = ' ';
  1049. term.line[y][x+1].mode &= ~ATTR_WDUMMY;
  1050. }
  1051. } else if (term.line[y][x].mode & ATTR_WDUMMY) {
  1052. term.line[y][x-1].u = ' ';
  1053. term.line[y][x-1].mode &= ~ATTR_WIDE;
  1054. }
  1055. term.dirty[y] = 1;
  1056. term.line[y][x] = *attr;
  1057. term.line[y][x].u = u;
  1058. }
  1059. void
  1060. tclearregion(int x1, int y1, int x2, int y2)
  1061. {
  1062. int x, y, temp;
  1063. Glyph *gp;
  1064. if (x1 > x2)
  1065. temp = x1, x1 = x2, x2 = temp;
  1066. if (y1 > y2)
  1067. temp = y1, y1 = y2, y2 = temp;
  1068. LIMIT(x1, 0, term.col-1);
  1069. LIMIT(x2, 0, term.col-1);
  1070. LIMIT(y1, 0, term.row-1);
  1071. LIMIT(y2, 0, term.row-1);
  1072. for (y = y1; y <= y2; y++) {
  1073. term.dirty[y] = 1;
  1074. for (x = x1; x <= x2; x++) {
  1075. gp = &term.line[y][x];
  1076. if (selected(x, y))
  1077. selclear();
  1078. gp->fg = term.c.attr.fg;
  1079. gp->bg = term.c.attr.bg;
  1080. gp->mode = 0;
  1081. gp->u = ' ';
  1082. }
  1083. }
  1084. }
  1085. void
  1086. tdeletechar(int n)
  1087. {
  1088. int dst, src, size;
  1089. Glyph *line;
  1090. LIMIT(n, 0, term.col - term.c.x);
  1091. dst = term.c.x;
  1092. src = term.c.x + n;
  1093. size = term.col - src;
  1094. line = term.line[term.c.y];
  1095. memmove(&line[dst], &line[src], size * sizeof(Glyph));
  1096. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1097. }
  1098. void
  1099. tinsertblank(int n)
  1100. {
  1101. int dst, src, size;
  1102. Glyph *line;
  1103. LIMIT(n, 0, term.col - term.c.x);
  1104. dst = term.c.x + n;
  1105. src = term.c.x;
  1106. size = term.col - dst;
  1107. line = term.line[term.c.y];
  1108. memmove(&line[dst], &line[src], size * sizeof(Glyph));
  1109. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1110. }
  1111. void
  1112. tinsertblankline(int n)
  1113. {
  1114. if (BETWEEN(term.c.y, term.top, term.bot))
  1115. tscrolldown(term.c.y, n);
  1116. }
  1117. void
  1118. tdeleteline(int n)
  1119. {
  1120. if (BETWEEN(term.c.y, term.top, term.bot))
  1121. tscrollup(term.c.y, n);
  1122. }
  1123. int32_t
  1124. tdefcolor(int *attr, int *npar, int l)
  1125. {
  1126. int32_t idx = -1;
  1127. uint r, g, b;
  1128. switch (attr[*npar + 1]) {
  1129. case 2: /* direct color in RGB space */
  1130. if (*npar + 4 >= l) {
  1131. fprintf(stderr,
  1132. "erresc(38): Incorrect number of parameters (%d)\n",
  1133. *npar);
  1134. break;
  1135. }
  1136. r = attr[*npar + 2];
  1137. g = attr[*npar + 3];
  1138. b = attr[*npar + 4];
  1139. *npar += 4;
  1140. if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
  1141. fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
  1142. r, g, b);
  1143. else
  1144. idx = TRUECOLOR(r, g, b);
  1145. break;
  1146. case 5: /* indexed color */
  1147. if (*npar + 2 >= l) {
  1148. fprintf(stderr,
  1149. "erresc(38): Incorrect number of parameters (%d)\n",
  1150. *npar);
  1151. break;
  1152. }
  1153. *npar += 2;
  1154. if (!BETWEEN(attr[*npar], 0, 255))
  1155. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
  1156. else
  1157. idx = attr[*npar];
  1158. break;
  1159. case 0: /* implemented defined (only foreground) */
  1160. case 1: /* transparent */
  1161. case 3: /* direct color in CMY space */
  1162. case 4: /* direct color in CMYK space */
  1163. default:
  1164. fprintf(stderr,
  1165. "erresc(38): gfx attr %d unknown\n", attr[*npar]);
  1166. break;
  1167. }
  1168. return idx;
  1169. }
  1170. void
  1171. tsetattr(int *attr, int l)
  1172. {
  1173. int i;
  1174. int32_t idx;
  1175. for (i = 0; i < l; i++) {
  1176. switch (attr[i]) {
  1177. case 0:
  1178. term.c.attr.mode &= ~(
  1179. ATTR_BOLD |
  1180. ATTR_FAINT |
  1181. ATTR_ITALIC |
  1182. ATTR_UNDERLINE |
  1183. ATTR_BLINK |
  1184. ATTR_REVERSE |
  1185. ATTR_INVISIBLE |
  1186. ATTR_STRUCK );
  1187. term.c.attr.fg = defaultfg;
  1188. term.c.attr.bg = defaultbg;
  1189. break;
  1190. case 1:
  1191. term.c.attr.mode |= ATTR_BOLD;
  1192. break;
  1193. case 2:
  1194. term.c.attr.mode |= ATTR_FAINT;
  1195. break;
  1196. case 3:
  1197. term.c.attr.mode |= ATTR_ITALIC;
  1198. break;
  1199. case 4:
  1200. term.c.attr.mode |= ATTR_UNDERLINE;
  1201. break;
  1202. case 5: /* slow blink */
  1203. /* FALLTHROUGH */
  1204. case 6: /* rapid blink */
  1205. term.c.attr.mode |= ATTR_BLINK;
  1206. break;
  1207. case 7:
  1208. term.c.attr.mode |= ATTR_REVERSE;
  1209. break;
  1210. case 8:
  1211. term.c.attr.mode |= ATTR_INVISIBLE;
  1212. break;
  1213. case 9:
  1214. term.c.attr.mode |= ATTR_STRUCK;
  1215. break;
  1216. case 22:
  1217. term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
  1218. break;
  1219. case 23:
  1220. term.c.attr.mode &= ~ATTR_ITALIC;
  1221. break;
  1222. case 24:
  1223. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1224. break;
  1225. case 25:
  1226. term.c.attr.mode &= ~ATTR_BLINK;
  1227. break;
  1228. case 27:
  1229. term.c.attr.mode &= ~ATTR_REVERSE;
  1230. break;
  1231. case 28:
  1232. term.c.attr.mode &= ~ATTR_INVISIBLE;
  1233. break;
  1234. case 29:
  1235. term.c.attr.mode &= ~ATTR_STRUCK;
  1236. break;
  1237. case 38:
  1238. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1239. term.c.attr.fg = idx;
  1240. break;
  1241. case 39:
  1242. term.c.attr.fg = defaultfg;
  1243. break;
  1244. case 48:
  1245. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1246. term.c.attr.bg = idx;
  1247. break;
  1248. case 49:
  1249. term.c.attr.bg = defaultbg;
  1250. break;
  1251. default:
  1252. if (BETWEEN(attr[i], 30, 37)) {
  1253. term.c.attr.fg = attr[i] - 30;
  1254. } else if (BETWEEN(attr[i], 40, 47)) {
  1255. term.c.attr.bg = attr[i] - 40;
  1256. } else if (BETWEEN(attr[i], 90, 97)) {
  1257. term.c.attr.fg = attr[i] - 90 + 8;
  1258. } else if (BETWEEN(attr[i], 100, 107)) {
  1259. term.c.attr.bg = attr[i] - 100 + 8;
  1260. } else {
  1261. fprintf(stderr,
  1262. "erresc(default): gfx attr %d unknown\n",
  1263. attr[i]);
  1264. csidump();
  1265. }
  1266. break;
  1267. }
  1268. }
  1269. }
  1270. void
  1271. tsetscroll(int t, int b)
  1272. {
  1273. int temp;
  1274. LIMIT(t, 0, term.row-1);
  1275. LIMIT(b, 0, term.row-1);
  1276. if (t > b) {
  1277. temp = t;
  1278. t = b;
  1279. b = temp;
  1280. }
  1281. term.top = t;
  1282. term.bot = b;
  1283. }
  1284. void
  1285. tsetmode(int priv, int set, int *args, int narg)
  1286. {
  1287. int alt, *lim;
  1288. for (lim = args + narg; args < lim; ++args) {
  1289. if (priv) {
  1290. switch (*args) {
  1291. case 1: /* DECCKM -- Cursor key */
  1292. xsetmode(set, MODE_APPCURSOR);
  1293. break;
  1294. case 5: /* DECSCNM -- Reverse video */
  1295. xsetmode(set, MODE_REVERSE);
  1296. break;
  1297. case 6: /* DECOM -- Origin */
  1298. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1299. tmoveato(0, 0);
  1300. break;
  1301. case 7: /* DECAWM -- Auto wrap */
  1302. MODBIT(term.mode, set, MODE_WRAP);
  1303. break;
  1304. case 0: /* Error (IGNORED) */
  1305. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1306. case 3: /* DECCOLM -- Column (IGNORED) */
  1307. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1308. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1309. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1310. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1311. case 42: /* DECNRCM -- National characters (IGNORED) */
  1312. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1313. break;
  1314. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1315. xsetmode(!set, MODE_HIDE);
  1316. break;
  1317. case 9: /* X10 mouse compatibility mode */
  1318. xsetpointermotion(0);
  1319. xsetmode(0, MODE_MOUSE);
  1320. xsetmode(set, MODE_MOUSEX10);
  1321. break;
  1322. case 1000: /* 1000: report button press */
  1323. xsetpointermotion(0);
  1324. xsetmode(0, MODE_MOUSE);
  1325. xsetmode(set, MODE_MOUSEBTN);
  1326. break;
  1327. case 1002: /* 1002: report motion on button press */
  1328. xsetpointermotion(0);
  1329. xsetmode(0, MODE_MOUSE);
  1330. xsetmode(set, MODE_MOUSEMOTION);
  1331. break;
  1332. case 1003: /* 1003: enable all mouse motions */
  1333. xsetpointermotion(set);
  1334. xsetmode(0, MODE_MOUSE);
  1335. xsetmode(set, MODE_MOUSEMANY);
  1336. break;
  1337. case 1004: /* 1004: send focus events to tty */
  1338. xsetmode(set, MODE_FOCUS);
  1339. break;
  1340. case 1006: /* 1006: extended reporting mode */
  1341. xsetmode(set, MODE_MOUSESGR);
  1342. break;
  1343. case 1034:
  1344. xsetmode(set, MODE_8BIT);
  1345. break;
  1346. case 1049: /* swap screen & set/restore cursor as xterm */
  1347. if (!allowaltscreen)
  1348. break;
  1349. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1350. /* FALLTHROUGH */
  1351. case 47: /* swap screen */
  1352. case 1047:
  1353. if (!allowaltscreen)
  1354. break;
  1355. alt = IS_SET(MODE_ALTSCREEN);
  1356. if (alt) {
  1357. tclearregion(0, 0, term.col-1,
  1358. term.row-1);
  1359. }
  1360. if (set ^ alt) /* set is always 1 or 0 */
  1361. tswapscreen();
  1362. if (*args != 1049)
  1363. break;
  1364. /* FALLTHROUGH */
  1365. case 1048:
  1366. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1367. break;
  1368. case 2004: /* 2004: bracketed paste mode */
  1369. xsetmode(set, MODE_BRCKTPASTE);
  1370. break;
  1371. /* Not implemented mouse modes. See comments there. */
  1372. case 1001: /* mouse highlight mode; can hang the
  1373. terminal by design when implemented. */
  1374. case 1005: /* UTF-8 mouse mode; will confuse
  1375. applications not supporting UTF-8
  1376. and luit. */
  1377. case 1015: /* urxvt mangled mouse mode; incompatible
  1378. and can be mistaken for other control
  1379. codes. */
  1380. break;
  1381. default:
  1382. fprintf(stderr,
  1383. "erresc: unknown private set/reset mode %d\n",
  1384. *args);
  1385. break;
  1386. }
  1387. } else {
  1388. switch (*args) {
  1389. case 0: /* Error (IGNORED) */
  1390. break;
  1391. case 2:
  1392. xsetmode(set, MODE_KBDLOCK);
  1393. break;
  1394. case 4: /* IRM -- Insertion-replacement */
  1395. MODBIT(term.mode, set, MODE_INSERT);
  1396. break;
  1397. case 12: /* SRM -- Send/Receive */
  1398. MODBIT(term.mode, !set, MODE_ECHO);
  1399. break;
  1400. case 20: /* LNM -- Linefeed/new line */
  1401. MODBIT(term.mode, set, MODE_CRLF);
  1402. break;
  1403. default:
  1404. fprintf(stderr,
  1405. "erresc: unknown set/reset mode %d\n",
  1406. *args);
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. }
  1412. void
  1413. csihandle(void)
  1414. {
  1415. char buf[40];
  1416. int len;
  1417. switch (csiescseq.mode[0]) {
  1418. default:
  1419. unknown:
  1420. fprintf(stderr, "erresc: unknown csi ");
  1421. csidump();
  1422. /* die(""); */
  1423. break;
  1424. case '@': /* ICH -- Insert <n> blank char */
  1425. DEFAULT(csiescseq.arg[0], 1);
  1426. tinsertblank(csiescseq.arg[0]);
  1427. break;
  1428. case 'A': /* CUU -- Cursor <n> Up */
  1429. DEFAULT(csiescseq.arg[0], 1);
  1430. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1431. break;
  1432. case 'B': /* CUD -- Cursor <n> Down */
  1433. case 'e': /* VPR --Cursor <n> Down */
  1434. DEFAULT(csiescseq.arg[0], 1);
  1435. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1436. break;
  1437. case 'i': /* MC -- Media Copy */
  1438. switch (csiescseq.arg[0]) {
  1439. case 0:
  1440. tdump();
  1441. break;
  1442. case 1:
  1443. tdumpline(term.c.y);
  1444. break;
  1445. case 2:
  1446. tdumpsel();
  1447. break;
  1448. case 4:
  1449. term.mode &= ~MODE_PRINT;
  1450. break;
  1451. case 5:
  1452. term.mode |= MODE_PRINT;
  1453. break;
  1454. }
  1455. break;
  1456. case 'c': /* DA -- Device Attributes */
  1457. if (csiescseq.arg[0] == 0)
  1458. ttywrite(vtiden, strlen(vtiden), 0);
  1459. break;
  1460. case 'b': /* REP -- if last char is printable print it <n> more times */
  1461. DEFAULT(csiescseq.arg[0], 1);
  1462. if (term.lastc)
  1463. while (csiescseq.arg[0]-- > 0)
  1464. tputc(term.lastc);
  1465. break;
  1466. case 'C': /* CUF -- Cursor <n> Forward */
  1467. case 'a': /* HPR -- Cursor <n> Forward */
  1468. DEFAULT(csiescseq.arg[0], 1);
  1469. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1470. break;
  1471. case 'D': /* CUB -- Cursor <n> Backward */
  1472. DEFAULT(csiescseq.arg[0], 1);
  1473. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1474. break;
  1475. case 'E': /* CNL -- Cursor <n> Down and first col */
  1476. DEFAULT(csiescseq.arg[0], 1);
  1477. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1478. break;
  1479. case 'F': /* CPL -- Cursor <n> Up and first col */
  1480. DEFAULT(csiescseq.arg[0], 1);
  1481. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1482. break;
  1483. case 'g': /* TBC -- Tabulation clear */
  1484. switch (csiescseq.arg[0]) {
  1485. case 0: /* clear current tab stop */
  1486. term.tabs[term.c.x] = 0;
  1487. break;
  1488. case 3: /* clear all the tabs */
  1489. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1490. break;
  1491. default:
  1492. goto unknown;
  1493. }
  1494. break;
  1495. case 'G': /* CHA -- Move to <col> */
  1496. case '`': /* HPA */
  1497. DEFAULT(csiescseq.arg[0], 1);
  1498. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1499. break;
  1500. case 'H': /* CUP -- Move to <row> <col> */
  1501. case 'f': /* HVP */
  1502. DEFAULT(csiescseq.arg[0], 1);
  1503. DEFAULT(csiescseq.arg[1], 1);
  1504. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1505. break;
  1506. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1507. DEFAULT(csiescseq.arg[0], 1);
  1508. tputtab(csiescseq.arg[0]);
  1509. break;
  1510. case 'J': /* ED -- Clear screen */
  1511. switch (csiescseq.arg[0]) {
  1512. case 0: /* below */
  1513. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1514. if (term.c.y < term.row-1) {
  1515. tclearregion(0, term.c.y+1, term.col-1,
  1516. term.row-1);
  1517. }
  1518. break;
  1519. case 1: /* above */
  1520. if (term.c.y > 1)
  1521. tclearregion(0, 0, term.col-1, term.c.y-1);
  1522. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1523. break;
  1524. case 2: /* all */
  1525. tclearregion(0, 0, term.col-1, term.row-1);
  1526. break;
  1527. default:
  1528. goto unknown;
  1529. }
  1530. break;
  1531. case 'K': /* EL -- Clear line */
  1532. switch (csiescseq.arg[0]) {
  1533. case 0: /* right */
  1534. tclearregion(term.c.x, term.c.y, term.col-1,
  1535. term.c.y);
  1536. break;
  1537. case 1: /* left */
  1538. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1539. break;
  1540. case 2: /* all */
  1541. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1542. break;
  1543. }
  1544. break;
  1545. case 'S': /* SU -- Scroll <n> line up */
  1546. DEFAULT(csiescseq.arg[0], 1);
  1547. tscrollup(term.top, csiescseq.arg[0]);
  1548. break;
  1549. case 'T': /* SD -- Scroll <n> line down */
  1550. DEFAULT(csiescseq.arg[0], 1);
  1551. tscrolldown(term.top, csiescseq.arg[0]);
  1552. break;
  1553. case 'L': /* IL -- Insert <n> blank lines */
  1554. DEFAULT(csiescseq.arg[0], 1);
  1555. tinsertblankline(csiescseq.arg[0]);
  1556. break;
  1557. case 'l': /* RM -- Reset Mode */
  1558. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1559. break;
  1560. case 'M': /* DL -- Delete <n> lines */
  1561. DEFAULT(csiescseq.arg[0], 1);
  1562. tdeleteline(csiescseq.arg[0]);
  1563. break;
  1564. case 'X': /* ECH -- Erase <n> char */
  1565. DEFAULT(csiescseq.arg[0], 1);
  1566. tclearregion(term.c.x, term.c.y,
  1567. term.c.x + csiescseq.arg[0] - 1, term.c.y);
  1568. break;
  1569. case 'P': /* DCH -- Delete <n> char */
  1570. DEFAULT(csiescseq.arg[0], 1);
  1571. tdeletechar(csiescseq.arg[0]);
  1572. break;
  1573. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1574. DEFAULT(csiescseq.arg[0], 1);
  1575. tputtab(-csiescseq.arg[0]);
  1576. break;
  1577. case 'd': /* VPA -- Move to <row> */
  1578. DEFAULT(csiescseq.arg[0], 1);
  1579. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1580. break;
  1581. case 'h': /* SM -- Set terminal mode */
  1582. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1583. break;
  1584. case 'm': /* SGR -- Terminal attribute (color) */
  1585. tsetattr(csiescseq.arg, csiescseq.narg);
  1586. break;
  1587. case 'n': /* DSR – Device Status Report (cursor position) */
  1588. if (csiescseq.arg[0] == 6) {
  1589. len = snprintf(buf, sizeof(buf), "\033[%i;%iR",
  1590. term.c.y+1, term.c.x+1);
  1591. ttywrite(buf, len, 0);
  1592. }
  1593. break;
  1594. case 'r': /* DECSTBM -- Set Scrolling Region */
  1595. if (csiescseq.priv) {
  1596. goto unknown;
  1597. } else {
  1598. DEFAULT(csiescseq.arg[0], 1);
  1599. DEFAULT(csiescseq.arg[1], term.row);
  1600. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1601. tmoveato(0, 0);
  1602. }
  1603. break;
  1604. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1605. tcursor(CURSOR_SAVE);
  1606. break;
  1607. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1608. tcursor(CURSOR_LOAD);
  1609. break;
  1610. case ' ':
  1611. switch (csiescseq.mode[1]) {
  1612. case 'q': /* DECSCUSR -- Set Cursor Style */
  1613. if (xsetcursor(csiescseq.arg[0]))
  1614. goto unknown;
  1615. break;
  1616. default:
  1617. goto unknown;
  1618. }
  1619. break;
  1620. }
  1621. }
  1622. void
  1623. csidump(void)
  1624. {
  1625. size_t i;
  1626. uint c;
  1627. fprintf(stderr, "ESC[");
  1628. for (i = 0; i < csiescseq.len; i++) {
  1629. c = csiescseq.buf[i] & 0xff;
  1630. if (isprint(c)) {
  1631. putc(c, stderr);
  1632. } else if (c == '\n') {
  1633. fprintf(stderr, "(\\n)");
  1634. } else if (c == '\r') {
  1635. fprintf(stderr, "(\\r)");
  1636. } else if (c == 0x1b) {
  1637. fprintf(stderr, "(\\e)");
  1638. } else {
  1639. fprintf(stderr, "(%02x)", c);
  1640. }
  1641. }
  1642. putc('\n', stderr);
  1643. }
  1644. void
  1645. csireset(void)
  1646. {
  1647. memset(&csiescseq, 0, sizeof(csiescseq));
  1648. }
  1649. void
  1650. strhandle(void)
  1651. {
  1652. char *p = NULL, *dec;
  1653. int j, narg, par;
  1654. term.esc &= ~(ESC_STR_END|ESC_STR);
  1655. strparse();
  1656. par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
  1657. switch (strescseq.type) {
  1658. case ']': /* OSC -- Operating System Command */
  1659. switch (par) {
  1660. case 0:
  1661. case 1:
  1662. case 2:
  1663. if (narg > 1)
  1664. xsettitle(strescseq.args[1]);
  1665. return;
  1666. case 52:
  1667. if (narg > 2 && allowwindowops) {
  1668. dec = base64dec(strescseq.args[2]);
  1669. if (dec) {
  1670. xsetsel(dec);
  1671. xclipcopy();
  1672. } else {
  1673. fprintf(stderr, "erresc: invalid base64\n");
  1674. }
  1675. }
  1676. return;
  1677. case 4: /* color set */
  1678. if (narg < 3)
  1679. break;
  1680. p = strescseq.args[2];
  1681. /* FALLTHROUGH */
  1682. case 104: /* color reset, here p = NULL */
  1683. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  1684. if (xsetcolorname(j, p)) {
  1685. if (par == 104 && narg <= 1)
  1686. return; /* color reset without parameter */
  1687. fprintf(stderr, "erresc: invalid color j=%d, p=%s\n",
  1688. j, p ? p : "(null)");
  1689. } else {
  1690. /*
  1691. * TODO if defaultbg color is changed, borders
  1692. * are dirty
  1693. */
  1694. redraw();
  1695. }
  1696. return;
  1697. }
  1698. break;
  1699. case 'k': /* old title set compatibility */
  1700. xsettitle(strescseq.args[0]);
  1701. return;
  1702. case 'P': /* DCS -- Device Control String */
  1703. case '_': /* APC -- Application Program Command */
  1704. case '^': /* PM -- Privacy Message */
  1705. return;
  1706. }
  1707. fprintf(stderr, "erresc: unknown str ");
  1708. strdump();
  1709. }
  1710. void
  1711. strparse(void)
  1712. {
  1713. int c;
  1714. char *p = strescseq.buf;
  1715. strescseq.narg = 0;
  1716. strescseq.buf[strescseq.len] = '\0';
  1717. if (*p == '\0')
  1718. return;
  1719. while (strescseq.narg < STR_ARG_SIZ) {
  1720. strescseq.args[strescseq.narg++] = p;
  1721. while ((c = *p) != ';' && c != '\0')
  1722. ++p;
  1723. if (c == '\0')
  1724. return;
  1725. *p++ = '\0';
  1726. }
  1727. }
  1728. void
  1729. strdump(void)
  1730. {
  1731. size_t i;
  1732. uint c;
  1733. fprintf(stderr, "ESC%c", strescseq.type);
  1734. for (i = 0; i < strescseq.len; i++) {
  1735. c = strescseq.buf[i] & 0xff;
  1736. if (c == '\0') {
  1737. putc('\n', stderr);
  1738. return;
  1739. } else if (isprint(c)) {
  1740. putc(c, stderr);
  1741. } else if (c == '\n') {
  1742. fprintf(stderr, "(\\n)");
  1743. } else if (c == '\r') {
  1744. fprintf(stderr, "(\\r)");
  1745. } else if (c == 0x1b) {
  1746. fprintf(stderr, "(\\e)");
  1747. } else {
  1748. fprintf(stderr, "(%02x)", c);
  1749. }
  1750. }
  1751. fprintf(stderr, "ESC\\\n");
  1752. }
  1753. void
  1754. strreset(void)
  1755. {
  1756. strescseq = (STREscape){
  1757. .buf = xrealloc(strescseq.buf, STR_BUF_SIZ),
  1758. .siz = STR_BUF_SIZ,
  1759. };
  1760. }
  1761. void
  1762. sendbreak(const Arg *arg)
  1763. {
  1764. if (tcsendbreak(cmdfd, 0))
  1765. perror("Error sending break");
  1766. }
  1767. void
  1768. tprinter(char *s, size_t len)
  1769. {
  1770. if (iofd != -1 && xwrite(iofd, s, len) < 0) {
  1771. perror("Error writing to output file");
  1772. close(iofd);
  1773. iofd = -1;
  1774. }
  1775. }
  1776. void
  1777. toggleprinter(const Arg *arg)
  1778. {
  1779. term.mode ^= MODE_PRINT;
  1780. }
  1781. void
  1782. printscreen(const Arg *arg)
  1783. {
  1784. tdump();
  1785. }
  1786. void
  1787. printsel(const Arg *arg)
  1788. {
  1789. tdumpsel();
  1790. }
  1791. void
  1792. tdumpsel(void)
  1793. {
  1794. char *ptr;
  1795. if ((ptr = getsel())) {
  1796. tprinter(ptr, strlen(ptr));
  1797. free(ptr);
  1798. }
  1799. }
  1800. void
  1801. tdumpline(int n)
  1802. {
  1803. char buf[UTF_SIZ];
  1804. Glyph *bp, *end;
  1805. bp = &term.line[n][0];
  1806. end = &bp[MIN(tlinelen(n), term.col) - 1];
  1807. if (bp != end || bp->u != ' ') {
  1808. for ( ; bp <= end; ++bp)
  1809. tprinter(buf, utf8encode(bp->u, buf));
  1810. }
  1811. tprinter("\n", 1);
  1812. }
  1813. void
  1814. tdump(void)
  1815. {
  1816. int i;
  1817. for (i = 0; i < term.row; ++i)
  1818. tdumpline(i);
  1819. }
  1820. void
  1821. tputtab(int n)
  1822. {
  1823. uint x = term.c.x;
  1824. if (n > 0) {
  1825. while (x < term.col && n--)
  1826. for (++x; x < term.col && !term.tabs[x]; ++x)
  1827. /* nothing */ ;
  1828. } else if (n < 0) {
  1829. while (x > 0 && n++)
  1830. for (--x; x > 0 && !term.tabs[x]; --x)
  1831. /* nothing */ ;
  1832. }
  1833. term.c.x = LIMIT(x, 0, term.col-1);
  1834. }
  1835. void
  1836. tdefutf8(char ascii)
  1837. {
  1838. if (ascii == 'G')
  1839. term.mode |= MODE_UTF8;
  1840. else if (ascii == '@')
  1841. term.mode &= ~MODE_UTF8;
  1842. }
  1843. void
  1844. tdeftran(char ascii)
  1845. {
  1846. static char cs[] = "0B";
  1847. static int vcs[] = {CS_GRAPHIC0, CS_USA};
  1848. char *p;
  1849. if ((p = strchr(cs, ascii)) == NULL) {
  1850. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1851. } else {
  1852. term.trantbl[term.icharset] = vcs[p - cs];
  1853. }
  1854. }
  1855. void
  1856. tdectest(char c)
  1857. {
  1858. int x, y;
  1859. if (c == '8') { /* DEC screen alignment test. */
  1860. for (x = 0; x < term.col; ++x) {
  1861. for (y = 0; y < term.row; ++y)
  1862. tsetchar('E', &term.c.attr, x, y);
  1863. }
  1864. }
  1865. }
  1866. void
  1867. tstrsequence(uchar c)
  1868. {
  1869. switch (c) {
  1870. case 0x90: /* DCS -- Device Control String */
  1871. c = 'P';
  1872. break;
  1873. case 0x9f: /* APC -- Application Program Command */
  1874. c = '_';
  1875. break;
  1876. case 0x9e: /* PM -- Privacy Message */
  1877. c = '^';
  1878. break;
  1879. case 0x9d: /* OSC -- Operating System Command */
  1880. c = ']';
  1881. break;
  1882. }
  1883. strreset();
  1884. strescseq.type = c;
  1885. term.esc |= ESC_STR;
  1886. }
  1887. void
  1888. tcontrolcode(uchar ascii)
  1889. {
  1890. switch (ascii) {
  1891. case '\t': /* HT */
  1892. tputtab(1);
  1893. return;
  1894. case '\b': /* BS */
  1895. tmoveto(term.c.x-1, term.c.y);
  1896. return;
  1897. case '\r': /* CR */
  1898. tmoveto(0, term.c.y);
  1899. return;
  1900. case '\f': /* LF */
  1901. case '\v': /* VT */
  1902. case '\n': /* LF */
  1903. /* go to first col if the mode is set */
  1904. tnewline(IS_SET(MODE_CRLF));
  1905. return;
  1906. case '\a': /* BEL */
  1907. if (term.esc & ESC_STR_END) {
  1908. /* backwards compatibility to xterm */
  1909. strhandle();
  1910. } else {
  1911. xbell();
  1912. }
  1913. break;
  1914. case '\033': /* ESC */
  1915. csireset();
  1916. term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
  1917. term.esc |= ESC_START;
  1918. return;
  1919. case '\016': /* SO (LS1 -- Locking shift 1) */
  1920. case '\017': /* SI (LS0 -- Locking shift 0) */
  1921. term.charset = 1 - (ascii - '\016');
  1922. return;
  1923. case '\032': /* SUB */
  1924. tsetchar('?', &term.c.attr, term.c.x, term.c.y);
  1925. /* FALLTHROUGH */
  1926. case '\030': /* CAN */
  1927. csireset();
  1928. break;
  1929. case '\005': /* ENQ (IGNORED) */
  1930. case '\000': /* NUL (IGNORED) */
  1931. case '\021': /* XON (IGNORED) */
  1932. case '\023': /* XOFF (IGNORED) */
  1933. case 0177: /* DEL (IGNORED) */
  1934. return;
  1935. case 0x80: /* TODO: PAD */
  1936. case 0x81: /* TODO: HOP */
  1937. case 0x82: /* TODO: BPH */
  1938. case 0x83: /* TODO: NBH */
  1939. case 0x84: /* TODO: IND */
  1940. break;
  1941. case 0x85: /* NEL -- Next line */
  1942. tnewline(1); /* always go to first col */
  1943. break;
  1944. case 0x86: /* TODO: SSA */
  1945. case 0x87: /* TODO: ESA */
  1946. break;
  1947. case 0x88: /* HTS -- Horizontal tab stop */
  1948. term.tabs[term.c.x] = 1;
  1949. break;
  1950. case 0x89: /* TODO: HTJ */
  1951. case 0x8a: /* TODO: VTS */
  1952. case 0x8b: /* TODO: PLD */
  1953. case 0x8c: /* TODO: PLU */
  1954. case 0x8d: /* TODO: RI */
  1955. case 0x8e: /* TODO: SS2 */
  1956. case 0x8f: /* TODO: SS3 */
  1957. case 0x91: /* TODO: PU1 */
  1958. case 0x92: /* TODO: PU2 */
  1959. case 0x93: /* TODO: STS */
  1960. case 0x94: /* TODO: CCH */
  1961. case 0x95: /* TODO: MW */
  1962. case 0x96: /* TODO: SPA */
  1963. case 0x97: /* TODO: EPA */
  1964. case 0x98: /* TODO: SOS */
  1965. case 0x99: /* TODO: SGCI */
  1966. break;
  1967. case 0x9a: /* DECID -- Identify Terminal */
  1968. ttywrite(vtiden, strlen(vtiden), 0);
  1969. break;
  1970. case 0x9b: /* TODO: CSI */
  1971. case 0x9c: /* TODO: ST */
  1972. break;
  1973. case 0x90: /* DCS -- Device Control String */
  1974. case 0x9d: /* OSC -- Operating System Command */
  1975. case 0x9e: /* PM -- Privacy Message */
  1976. case 0x9f: /* APC -- Application Program Command */
  1977. tstrsequence(ascii);
  1978. return;
  1979. }
  1980. /* only CAN, SUB, \a and C1 chars interrupt a sequence */
  1981. term.esc &= ~(ESC_STR_END|ESC_STR);
  1982. }
  1983. /*
  1984. * returns 1 when the sequence is finished and it hasn't to read
  1985. * more characters for this sequence, otherwise 0
  1986. */
  1987. int
  1988. eschandle(uchar ascii)
  1989. {
  1990. switch (ascii) {
  1991. case '[':
  1992. term.esc |= ESC_CSI;
  1993. return 0;
  1994. case '#':
  1995. term.esc |= ESC_TEST;
  1996. return 0;
  1997. case '%':
  1998. term.esc |= ESC_UTF8;
  1999. return 0;
  2000. case 'P': /* DCS -- Device Control String */
  2001. case '_': /* APC -- Application Program Command */
  2002. case '^': /* PM -- Privacy Message */
  2003. case ']': /* OSC -- Operating System Command */
  2004. case 'k': /* old title set compatibility */
  2005. tstrsequence(ascii);
  2006. return 0;
  2007. case 'n': /* LS2 -- Locking shift 2 */
  2008. case 'o': /* LS3 -- Locking shift 3 */
  2009. term.charset = 2 + (ascii - 'n');
  2010. break;
  2011. case '(': /* GZD4 -- set primary charset G0 */
  2012. case ')': /* G1D4 -- set secondary charset G1 */
  2013. case '*': /* G2D4 -- set tertiary charset G2 */
  2014. case '+': /* G3D4 -- set quaternary charset G3 */
  2015. term.icharset = ascii - '(';
  2016. term.esc |= ESC_ALTCHARSET;
  2017. return 0;
  2018. case 'D': /* IND -- Linefeed */
  2019. if (term.c.y == term.bot) {
  2020. tscrollup(term.top, 1);
  2021. } else {
  2022. tmoveto(term.c.x, term.c.y+1);
  2023. }
  2024. break;
  2025. case 'E': /* NEL -- Next line */
  2026. tnewline(1); /* always go to first col */
  2027. break;
  2028. case 'H': /* HTS -- Horizontal tab stop */
  2029. term.tabs[term.c.x] = 1;
  2030. break;
  2031. case 'M': /* RI -- Reverse index */
  2032. if (term.c.y == term.top) {
  2033. tscrolldown(term.top, 1);
  2034. } else {
  2035. tmoveto(term.c.x, term.c.y-1);
  2036. }
  2037. break;
  2038. case 'Z': /* DECID -- Identify Terminal */
  2039. ttywrite(vtiden, strlen(vtiden), 0);
  2040. break;
  2041. case 'c': /* RIS -- Reset to initial state */
  2042. treset();
  2043. resettitle();
  2044. xloadcols();
  2045. break;
  2046. case '=': /* DECPAM -- Application keypad */
  2047. xsetmode(1, MODE_APPKEYPAD);
  2048. break;
  2049. case '>': /* DECPNM -- Normal keypad */
  2050. xsetmode(0, MODE_APPKEYPAD);
  2051. break;
  2052. case '7': /* DECSC -- Save Cursor */
  2053. tcursor(CURSOR_SAVE);
  2054. break;
  2055. case '8': /* DECRC -- Restore Cursor */
  2056. tcursor(CURSOR_LOAD);
  2057. break;
  2058. case '\\': /* ST -- String Terminator */
  2059. if (term.esc & ESC_STR_END)
  2060. strhandle();
  2061. break;
  2062. default:
  2063. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2064. (uchar) ascii, isprint(ascii)? ascii:'.');
  2065. break;
  2066. }
  2067. return 1;
  2068. }
  2069. void
  2070. tputc(Rune u)
  2071. {
  2072. char c[UTF_SIZ];
  2073. int control;
  2074. int width, len;
  2075. Glyph *gp;
  2076. control = ISCONTROL(u);
  2077. if (u < 127 || !IS_SET(MODE_UTF8)) {
  2078. c[0] = u;
  2079. width = len = 1;
  2080. } else {
  2081. len = utf8encode(u, c);
  2082. if (!control && (width = wcwidth(u)) == -1)
  2083. width = 1;
  2084. }
  2085. if (IS_SET(MODE_PRINT))
  2086. tprinter(c, len);
  2087. /*
  2088. * STR sequence must be checked before anything else
  2089. * because it uses all following characters until it
  2090. * receives a ESC, a SUB, a ST or any other C1 control
  2091. * character.
  2092. */
  2093. if (term.esc & ESC_STR) {
  2094. if (u == '\a' || u == 030 || u == 032 || u == 033 ||
  2095. ISCONTROLC1(u)) {
  2096. term.esc &= ~(ESC_START|ESC_STR);
  2097. term.esc |= ESC_STR_END;
  2098. goto check_control_code;
  2099. }
  2100. if (strescseq.len+len >= strescseq.siz) {
  2101. /*
  2102. * Here is a bug in terminals. If the user never sends
  2103. * some code to stop the str or esc command, then st
  2104. * will stop responding. But this is better than
  2105. * silently failing with unknown characters. At least
  2106. * then users will report back.
  2107. *
  2108. * In the case users ever get fixed, here is the code:
  2109. */
  2110. /*
  2111. * term.esc = 0;
  2112. * strhandle();
  2113. */
  2114. if (strescseq.siz > (SIZE_MAX - UTF_SIZ) / 2)
  2115. return;
  2116. strescseq.siz *= 2;
  2117. strescseq.buf = xrealloc(strescseq.buf, strescseq.siz);
  2118. }
  2119. memmove(&strescseq.buf[strescseq.len], c, len);
  2120. strescseq.len += len;
  2121. return;
  2122. }
  2123. check_control_code:
  2124. /*
  2125. * Actions of control codes must be performed as soon they arrive
  2126. * because they can be embedded inside a control sequence, and
  2127. * they must not cause conflicts with sequences.
  2128. */
  2129. if (control) {
  2130. tcontrolcode(u);
  2131. /*
  2132. * control codes are not shown ever
  2133. */
  2134. if (!term.esc)
  2135. term.lastc = 0;
  2136. return;
  2137. } else if (term.esc & ESC_START) {
  2138. if (term.esc & ESC_CSI) {
  2139. csiescseq.buf[csiescseq.len++] = u;
  2140. if (BETWEEN(u, 0x40, 0x7E)
  2141. || csiescseq.len >= \
  2142. sizeof(csiescseq.buf)-1) {
  2143. term.esc = 0;
  2144. csiparse();
  2145. csihandle();
  2146. }
  2147. return;
  2148. } else if (term.esc & ESC_UTF8) {
  2149. tdefutf8(u);
  2150. } else if (term.esc & ESC_ALTCHARSET) {
  2151. tdeftran(u);
  2152. } else if (term.esc & ESC_TEST) {
  2153. tdectest(u);
  2154. } else {
  2155. if (!eschandle(u))
  2156. return;
  2157. /* sequence already finished */
  2158. }
  2159. term.esc = 0;
  2160. /*
  2161. * All characters which form part of a sequence are not
  2162. * printed
  2163. */
  2164. return;
  2165. }
  2166. if (selected(term.c.x, term.c.y))
  2167. selclear();
  2168. gp = &term.line[term.c.y][term.c.x];
  2169. if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2170. gp->mode |= ATTR_WRAP;
  2171. tnewline(1);
  2172. gp = &term.line[term.c.y][term.c.x];
  2173. }
  2174. if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
  2175. memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
  2176. if (term.c.x+width > term.col) {
  2177. tnewline(1);
  2178. gp = &term.line[term.c.y][term.c.x];
  2179. }
  2180. tsetchar(u, &term.c.attr, term.c.x, term.c.y);
  2181. term.lastc = u;
  2182. if (width == 2) {
  2183. gp->mode |= ATTR_WIDE;
  2184. if (term.c.x+1 < term.col) {
  2185. gp[1].u = '\0';
  2186. gp[1].mode = ATTR_WDUMMY;
  2187. }
  2188. }
  2189. if (term.c.x+width < term.col) {
  2190. tmoveto(term.c.x+width, term.c.y);
  2191. } else {
  2192. term.c.state |= CURSOR_WRAPNEXT;
  2193. }
  2194. }
  2195. int
  2196. twrite(const char *buf, int buflen, int show_ctrl)
  2197. {
  2198. int charsize;
  2199. Rune u;
  2200. int n;
  2201. for (n = 0; n < buflen; n += charsize) {
  2202. if (IS_SET(MODE_UTF8)) {
  2203. /* process a complete utf8 char */
  2204. charsize = utf8decode(buf + n, &u, buflen - n);
  2205. if (charsize == 0)
  2206. break;
  2207. } else {
  2208. u = buf[n] & 0xFF;
  2209. charsize = 1;
  2210. }
  2211. if (show_ctrl && ISCONTROL(u)) {
  2212. if (u & 0x80) {
  2213. u &= 0x7f;
  2214. tputc('^');
  2215. tputc('[');
  2216. } else if (u != '\n' && u != '\r' && u != '\t') {
  2217. u ^= 0x40;
  2218. tputc('^');
  2219. }
  2220. }
  2221. tputc(u);
  2222. }
  2223. return n;
  2224. }
  2225. void
  2226. tresize(int col, int row)
  2227. {
  2228. int i;
  2229. int minrow = MIN(row, term.row);
  2230. int mincol = MIN(col, term.col);
  2231. int *bp;
  2232. TCursor c;
  2233. if (col < 1 || row < 1) {
  2234. fprintf(stderr,
  2235. "tresize: error resizing to %dx%d\n", col, row);
  2236. return;
  2237. }
  2238. /*
  2239. * slide screen to keep cursor where we expect it -
  2240. * tscrollup would work here, but we can optimize to
  2241. * memmove because we're freeing the earlier lines
  2242. */
  2243. for (i = 0; i <= term.c.y - row; i++) {
  2244. free(term.line[i]);
  2245. free(term.alt[i]);
  2246. }
  2247. /* ensure that both src and dst are not NULL */
  2248. if (i > 0) {
  2249. memmove(term.line, term.line + i, row * sizeof(Line));
  2250. memmove(term.alt, term.alt + i, row * sizeof(Line));
  2251. }
  2252. for (i += row; i < term.row; i++) {
  2253. free(term.line[i]);
  2254. free(term.alt[i]);
  2255. }
  2256. /* resize to new height */
  2257. term.line = xrealloc(term.line, row * sizeof(Line));
  2258. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2259. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2260. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2261. /* resize each row to new width, zero-pad if needed */
  2262. for (i = 0; i < minrow; i++) {
  2263. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2264. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2265. }
  2266. /* allocate any new rows */
  2267. for (/* i = minrow */; i < row; i++) {
  2268. term.line[i] = xmalloc(col * sizeof(Glyph));
  2269. term.alt[i] = xmalloc(col * sizeof(Glyph));
  2270. }
  2271. if (col > term.col) {
  2272. bp = term.tabs + term.col;
  2273. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2274. while (--bp > term.tabs && !*bp)
  2275. /* nothing */ ;
  2276. for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2277. *bp = 1;
  2278. }
  2279. /* update terminal size */
  2280. term.col = col;
  2281. term.row = row;
  2282. /* reset scrolling region */
  2283. tsetscroll(0, row-1);
  2284. /* make use of the LIMIT in tmoveto */
  2285. tmoveto(term.c.x, term.c.y);
  2286. /* Clearing both screens (it makes dirty all lines) */
  2287. c = term.c;
  2288. for (i = 0; i < 2; i++) {
  2289. if (mincol < col && 0 < minrow) {
  2290. tclearregion(mincol, 0, col - 1, minrow - 1);
  2291. }
  2292. if (0 < col && minrow < row) {
  2293. tclearregion(0, minrow, col - 1, row - 1);
  2294. }
  2295. tswapscreen();
  2296. tcursor(CURSOR_LOAD);
  2297. }
  2298. term.c = c;
  2299. }
  2300. void
  2301. resettitle(void)
  2302. {
  2303. xsettitle(NULL);
  2304. }
  2305. void
  2306. drawregion(int x1, int y1, int x2, int y2)
  2307. {
  2308. int y;
  2309. for (y = y1; y < y2; y++) {
  2310. if (!term.dirty[y])
  2311. continue;
  2312. term.dirty[y] = 0;
  2313. xdrawline(term.line[y], x1, y, x2);
  2314. }
  2315. }
  2316. void
  2317. draw(void)
  2318. {
  2319. int cx = term.c.x, ocx = term.ocx, ocy = term.ocy;
  2320. if (!xstartdraw())
  2321. return;
  2322. /* adjust cursor position */
  2323. LIMIT(term.ocx, 0, term.col-1);
  2324. LIMIT(term.ocy, 0, term.row-1);
  2325. if (term.line[term.ocy][term.ocx].mode & ATTR_WDUMMY)
  2326. term.ocx--;
  2327. if (term.line[term.c.y][cx].mode & ATTR_WDUMMY)
  2328. cx--;
  2329. drawregion(0, 0, term.col, term.row);
  2330. xdrawcursor(cx, term.c.y, term.line[term.c.y][cx],
  2331. term.ocx, term.ocy, term.line[term.ocy][term.ocx]);
  2332. term.ocx = cx;
  2333. term.ocy = term.c.y;
  2334. xfinishdraw();
  2335. if (ocx != term.ocx || ocy != term.ocy)
  2336. xximspot(term.ocx, term.ocy);
  2337. }
  2338. void
  2339. redraw(void)
  2340. {
  2341. tfulldirt();
  2342. draw();
  2343. }