My build of the simple terminal from suckless.org.
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 

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