ST patched with stuff from https://st.suckless.org/patches/ to work as a lighter alternative to XTerm
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.

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