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.

2673 lines
56 KiB

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