Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2608 lines
55 KiB

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