My build of suckless st terminal
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.

2650 lines
54 KiB

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