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.

1880 lines
42 KiB

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
14 years ago
14 years ago
15 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
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 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
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
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
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
14 years ago
15 years ago
14 years ago
14 years ago
  1. /* See LICENSE for licence details. */
  2. #define _XOPEN_SOURCE 600
  3. #include <ctype.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <limits.h>
  7. #include <locale.h>
  8. #include <stdarg.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <signal.h>
  13. #include <sys/ioctl.h>
  14. #include <sys/select.h>
  15. #include <sys/stat.h>
  16. #include <sys/types.h>
  17. #include <sys/wait.h>
  18. #include <unistd.h>
  19. #include <X11/Xatom.h>
  20. #include <X11/Xlib.h>
  21. #include <X11/Xutil.h>
  22. #include <X11/cursorfont.h>
  23. #include <X11/keysym.h>
  24. #if defined(__linux)
  25. #include <pty.h>
  26. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  27. #include <util.h>
  28. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  29. #include <libutil.h>
  30. #endif
  31. #define USAGE \
  32. "st-" VERSION ", (c) 2010 st engineers\n" \
  33. "usage: st [-t title] [-c class] [-e cmd] [-v]\n"
  34. /* Arbitrary sizes */
  35. #define ESC_TITLE_SIZ 256
  36. #define ESC_BUF_SIZ 256
  37. #define ESC_ARG_SIZ 16
  38. #define DRAW_BUF_SIZ 1024
  39. #define UTF_SIZ 4
  40. #define SERRNO strerror(errno)
  41. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  42. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  43. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  44. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  45. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  46. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  47. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  48. #define IS_SET(flag) (term.mode & (flag))
  49. /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
  50. enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
  51. enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT,
  52. CURSOR_SAVE, CURSOR_LOAD };
  53. enum { CURSOR_DEFAULT = 0, CURSOR_HIDE = 1, CURSOR_WRAPNEXT = 2 };
  54. enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
  55. enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4, MODE_ALTSCREEN=8,
  56. MODE_CRLF=16 };
  57. enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
  58. enum { SCREEN_UPDATE, SCREEN_REDRAW };
  59. enum { WIN_VISIBLE=1, WIN_REDRAW=2, WIN_FOCUSED=4 };
  60. #undef B0
  61. enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
  62. typedef struct {
  63. char c[UTF_SIZ]; /* character code */
  64. char mode; /* attribute flags */
  65. int fg; /* foreground */
  66. int bg; /* background */
  67. char state; /* state flags */
  68. } Glyph;
  69. typedef Glyph* Line;
  70. typedef struct {
  71. Glyph attr; /* current char attributes */
  72. int x;
  73. int y;
  74. char state;
  75. } TCursor;
  76. /* CSI Escape sequence structs */
  77. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  78. typedef struct {
  79. char buf[ESC_BUF_SIZ]; /* raw string */
  80. int len; /* raw string length */
  81. char priv;
  82. int arg[ESC_ARG_SIZ];
  83. int narg; /* nb of args */
  84. char mode;
  85. } CSIEscape;
  86. /* Internal representation of the screen */
  87. typedef struct {
  88. int row; /* nb row */
  89. int col; /* nb col */
  90. Line* line; /* screen */
  91. Line* alt; /* alternate screen */
  92. TCursor c; /* cursor */
  93. int top; /* top scroll limit */
  94. int bot; /* bottom scroll limit */
  95. int mode; /* terminal mode flags */
  96. int esc; /* escape state flags */
  97. char title[ESC_TITLE_SIZ];
  98. int titlelen;
  99. } Term;
  100. /* Purely graphic info */
  101. typedef struct {
  102. Display* dpy;
  103. Colormap cmap;
  104. Window win;
  105. Pixmap buf;
  106. XIM xim;
  107. XIC xic;
  108. int scr;
  109. int w; /* window width */
  110. int h; /* window height */
  111. int bufw; /* pixmap width */
  112. int bufh; /* pixmap height */
  113. int ch; /* char height */
  114. int cw; /* char width */
  115. char state; /* focus, redraw, visible */
  116. } XWindow;
  117. typedef struct {
  118. KeySym k;
  119. char s[ESC_BUF_SIZ];
  120. } Key;
  121. /* Drawing Context */
  122. typedef struct {
  123. unsigned long col[256];
  124. GC gc;
  125. struct {
  126. int ascent;
  127. int descent;
  128. short lbearing;
  129. short rbearing;
  130. XFontSet set;
  131. } font, bfont;
  132. } DC;
  133. /* TODO: use better name for vars... */
  134. typedef struct {
  135. int mode;
  136. int bx, by;
  137. int ex, ey;
  138. struct {int x, y;} b, e;
  139. char *clip;
  140. } Selection;
  141. #include "config.h"
  142. static void die(const char *errstr, ...);
  143. static void draw(int);
  144. static void execsh(void);
  145. static void sigchld(int);
  146. static void run(void);
  147. static void csidump(void);
  148. static void csihandle(void);
  149. static void csiparse(void);
  150. static void csireset(void);
  151. static void tclearregion(int, int, int, int);
  152. static void tcursor(int);
  153. static void tdeletechar(int);
  154. static void tdeleteline(int);
  155. static void tinsertblank(int);
  156. static void tinsertblankline(int);
  157. static void tmoveto(int, int);
  158. static void tnew(int, int);
  159. static void tnewline(int);
  160. static void tputtab(void);
  161. static void tputc(char*);
  162. static void treset(void);
  163. static int tresize(int, int);
  164. static void tscrollup(int, int);
  165. static void tscrolldown(int, int);
  166. static void tsetattr(int*, int);
  167. static void tsetchar(char*);
  168. static void tsetscroll(int, int);
  169. static void tswapscreen(void);
  170. static void ttynew(void);
  171. static void ttyread(void);
  172. static void ttyresize(int, int);
  173. static void ttywrite(const char *, size_t);
  174. static void xdraws(char *, Glyph, int, int, int, int);
  175. static void xhints(void);
  176. static void xclear(int, int, int, int);
  177. static void xdrawcursor(void);
  178. static void xinit(void);
  179. static void xloadcols(void);
  180. static void xseturgency(int);
  181. static void xsetsel(char*);
  182. static void xresize(int, int);
  183. static void expose(XEvent *);
  184. static void visibility(XEvent *);
  185. static void unmap(XEvent *);
  186. static char* kmap(KeySym);
  187. static void kpress(XEvent *);
  188. static void resize(XEvent *);
  189. static void focus(XEvent *);
  190. static void brelease(XEvent *);
  191. static void bpress(XEvent *);
  192. static void bmotion(XEvent *);
  193. static void selnotify(XEvent *);
  194. static void selrequest(XEvent *);
  195. static void selinit(void);
  196. static inline int selected(int, int);
  197. static void selcopy(void);
  198. static void selpaste(void);
  199. static int utf8decode(char *, long *);
  200. static int utf8encode(long *, char *);
  201. static int utf8size(char *);
  202. static int isfullutf8(char *, int);
  203. static void (*handler[LASTEvent])(XEvent *) = {
  204. [KeyPress] = kpress,
  205. [ConfigureNotify] = resize,
  206. [VisibilityNotify] = visibility,
  207. [UnmapNotify] = unmap,
  208. [Expose] = expose,
  209. [FocusIn] = focus,
  210. [FocusOut] = focus,
  211. [MotionNotify] = bmotion,
  212. [ButtonPress] = bpress,
  213. [ButtonRelease] = brelease,
  214. [SelectionNotify] = selnotify,
  215. [SelectionRequest] = selrequest,
  216. };
  217. /* Globals */
  218. static DC dc;
  219. static XWindow xw;
  220. static Term term;
  221. static CSIEscape escseq;
  222. static int cmdfd;
  223. static pid_t pid;
  224. static Selection sel;
  225. static char **opt_cmd = NULL;
  226. static char *opt_title = NULL;
  227. static char *opt_class = NULL;
  228. int
  229. utf8decode(char *s, long *u) {
  230. unsigned char c;
  231. int i, n, rtn;
  232. rtn = 1;
  233. c = *s;
  234. if(~c&B7) { /* 0xxxxxxx */
  235. *u = c;
  236. return rtn;
  237. } else if((c&(B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
  238. *u = c&(B4|B3|B2|B1|B0);
  239. n = 1;
  240. } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
  241. *u = c&(B3|B2|B1|B0);
  242. n = 2;
  243. } else if((c&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
  244. *u = c&(B2|B1|B0);
  245. n = 3;
  246. } else
  247. goto invalid;
  248. for(i=n,++s; i>0; --i,++rtn,++s) {
  249. c = *s;
  250. if((c&(B7|B6)) != B7) /* 10xxxxxx */
  251. goto invalid;
  252. *u <<= 6;
  253. *u |= c&(B5|B4|B3|B2|B1|B0);
  254. }
  255. if((n == 1 && *u < 0x80) ||
  256. (n == 2 && *u < 0x800) ||
  257. (n == 3 && *u < 0x10000) ||
  258. (*u >= 0xD800 && *u <= 0xDFFF))
  259. goto invalid;
  260. return rtn;
  261. invalid:
  262. *u = 0xFFFD;
  263. return rtn;
  264. }
  265. int
  266. utf8encode(long *u, char *s) {
  267. unsigned char *sp;
  268. unsigned long uc;
  269. int i, n;
  270. sp = (unsigned char*) s;
  271. uc = *u;
  272. if(uc < 0x80) {
  273. *sp = uc; /* 0xxxxxxx */
  274. return 1;
  275. } else if(*u < 0x800) {
  276. *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
  277. n = 1;
  278. } else if(uc < 0x10000) {
  279. *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
  280. n = 2;
  281. } else if(uc <= 0x10FFFF) {
  282. *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
  283. n = 3;
  284. } else {
  285. goto invalid;
  286. }
  287. for(i=n,++sp; i>0; --i,++sp)
  288. *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
  289. return n+1;
  290. invalid:
  291. /* U+FFFD */
  292. *s++ = '\xEF';
  293. *s++ = '\xBF';
  294. *s = '\xBD';
  295. return 3;
  296. }
  297. /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
  298. UTF-8 otherwise return 0 */
  299. int
  300. isfullutf8(char *s, int b) {
  301. unsigned char *c1, *c2, *c3;
  302. c1 = (unsigned char *) s;
  303. c2 = (unsigned char *) ++s;
  304. c3 = (unsigned char *) ++s;
  305. if(b < 1)
  306. return 0;
  307. else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
  308. return 0;
  309. else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
  310. ((b == 1) ||
  311. ((b == 2) && (*c2&(B7|B6)) == B7)))
  312. return 0;
  313. else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
  314. ((b == 1) ||
  315. ((b == 2) && (*c2&(B7|B6)) == B7) ||
  316. ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
  317. return 0;
  318. else
  319. return 1;
  320. }
  321. int
  322. utf8size(char *s) {
  323. unsigned char c = *s;
  324. if (~c&B7)
  325. return 1;
  326. else if ((c&(B7|B6|B5)) == (B7|B6))
  327. return 2;
  328. else if ((c&(B7|B6|B5|B4)) == (B7|B6|B5))
  329. return 3;
  330. else
  331. return 4;
  332. }
  333. void
  334. selinit(void) {
  335. sel.mode = 0;
  336. sel.bx = -1;
  337. sel.clip = NULL;
  338. }
  339. static inline int
  340. selected(int x, int y) {
  341. if(sel.ey == y && sel.by == y) {
  342. int bx = MIN(sel.bx, sel.ex);
  343. int ex = MAX(sel.bx, sel.ex);
  344. return BETWEEN(x, bx, ex);
  345. }
  346. return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
  347. || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
  348. }
  349. void
  350. getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
  351. if(b)
  352. *b = e->xbutton.button;
  353. *x = e->xbutton.x/xw.cw;
  354. *y = e->xbutton.y/xw.ch;
  355. sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
  356. sel.b.y = MIN(sel.by, sel.ey);
  357. sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
  358. sel.e.y = MAX(sel.by, sel.ey);
  359. }
  360. void
  361. bpress(XEvent *e) {
  362. sel.mode = 1;
  363. sel.ex = sel.bx = e->xbutton.x/xw.cw;
  364. sel.ey = sel.by = e->xbutton.y/xw.ch;
  365. }
  366. void
  367. selcopy(void) {
  368. char *str, *ptr;
  369. int x, y, sz, sl, ls = 0;
  370. if(sel.bx == -1)
  371. str = NULL;
  372. else {
  373. sz = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
  374. ptr = str = malloc(sz);
  375. for(y = 0; y < term.row; y++) {
  376. for(x = 0; x < term.col; x++)
  377. if(term.line[y][x].state & GLYPH_SET && (ls = selected(x, y))) {
  378. sl = utf8size(term.line[y][x].c);
  379. memcpy(ptr, term.line[y][x].c, sl);
  380. ptr += sl;
  381. }
  382. if(ls)
  383. *ptr = '\n', ptr++;
  384. }
  385. *ptr = 0;
  386. }
  387. xsetsel(str);
  388. }
  389. void
  390. selnotify(XEvent *e) {
  391. unsigned long nitems;
  392. unsigned long ofs, rem;
  393. int format;
  394. unsigned char *data;
  395. Atom type;
  396. ofs = 0;
  397. do {
  398. if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
  399. False, AnyPropertyType, &type, &format,
  400. &nitems, &rem, &data)) {
  401. fprintf(stderr, "Clipboard allocation failed\n");
  402. return;
  403. }
  404. ttywrite((const char *) data, nitems * format / 8);
  405. XFree(data);
  406. /* number of 32-bit chunks returned */
  407. ofs += nitems * format / 32;
  408. } while(rem > 0);
  409. }
  410. void
  411. selpaste() {
  412. XConvertSelection(xw.dpy, XA_PRIMARY, XA_STRING, XA_PRIMARY, xw.win, CurrentTime);
  413. }
  414. void
  415. selrequest(XEvent *e) {
  416. XSelectionRequestEvent *xsre;
  417. XSelectionEvent xev;
  418. Atom xa_targets;
  419. xsre = (XSelectionRequestEvent *) e;
  420. xev.type = SelectionNotify;
  421. xev.requestor = xsre->requestor;
  422. xev.selection = xsre->selection;
  423. xev.target = xsre->target;
  424. xev.time = xsre->time;
  425. /* reject */
  426. xev.property = None;
  427. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  428. if(xsre->target == xa_targets) {
  429. /* respond with the supported type */
  430. Atom string = XA_STRING;
  431. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  432. XA_ATOM, 32, PropModeReplace,
  433. (unsigned char *) &string, 1);
  434. xev.property = xsre->property;
  435. } else if(xsre->target == XA_STRING) {
  436. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  437. xsre->target, 8, PropModeReplace,
  438. (unsigned char *) sel.clip, strlen(sel.clip));
  439. xev.property = xsre->property;
  440. }
  441. /* all done, send a notification to the listener */
  442. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  443. fprintf(stderr, "Error sending SelectionNotify event\n");
  444. }
  445. void
  446. xsetsel(char *str) {
  447. /* register the selection for both the clipboard and the primary */
  448. Atom clipboard;
  449. free(sel.clip);
  450. sel.clip = str;
  451. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
  452. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  453. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  454. XFlush(xw.dpy);
  455. }
  456. /* TODO: doubleclick to select word */
  457. void
  458. brelease(XEvent *e) {
  459. int b;
  460. sel.mode = 0;
  461. getbuttoninfo(e, &b, &sel.ex, &sel.ey);
  462. if(sel.bx==sel.ex && sel.by==sel.ey) {
  463. sel.bx = -1;
  464. if(b==2)
  465. selpaste();
  466. } else {
  467. if(b==1)
  468. selcopy();
  469. }
  470. draw(1);
  471. }
  472. void
  473. bmotion(XEvent *e) {
  474. if (sel.mode) {
  475. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  476. /* XXX: draw() can't keep up, disabled for now.
  477. selection is visible on button release.
  478. draw(1); */
  479. }
  480. }
  481. void
  482. die(const char *errstr, ...) {
  483. va_list ap;
  484. va_start(ap, errstr);
  485. vfprintf(stderr, errstr, ap);
  486. va_end(ap);
  487. exit(EXIT_FAILURE);
  488. }
  489. void
  490. execsh(void) {
  491. char **args;
  492. char *envshell = getenv("SHELL");
  493. DEFAULT(envshell, "sh");
  494. putenv("TERM="TNAME);
  495. args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
  496. execvp(args[0], args);
  497. exit(EXIT_FAILURE);
  498. }
  499. void
  500. sigchld(int a) {
  501. int stat = 0;
  502. if(waitpid(pid, &stat, 0) < 0)
  503. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  504. if(WIFEXITED(stat))
  505. exit(WEXITSTATUS(stat));
  506. else
  507. exit(EXIT_FAILURE);
  508. }
  509. void
  510. ttynew(void) {
  511. int m, s;
  512. /* seems to work fine on linux, openbsd and freebsd */
  513. struct winsize w = {term.row, term.col, 0, 0};
  514. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  515. die("openpty failed: %s\n", SERRNO);
  516. switch(pid = fork()) {
  517. case -1:
  518. die("fork failed\n");
  519. break;
  520. case 0:
  521. setsid(); /* create a new process group */
  522. dup2(s, STDIN_FILENO);
  523. dup2(s, STDOUT_FILENO);
  524. dup2(s, STDERR_FILENO);
  525. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  526. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  527. close(s);
  528. close(m);
  529. execsh();
  530. break;
  531. default:
  532. close(s);
  533. cmdfd = m;
  534. signal(SIGCHLD, sigchld);
  535. }
  536. }
  537. void
  538. dump(char c) {
  539. static int col;
  540. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  541. if(++col % 10 == 0)
  542. fprintf(stderr, "\n");
  543. }
  544. void
  545. ttyread(void) {
  546. static char buf[BUFSIZ];
  547. static int buflen = 0;
  548. char *ptr;
  549. char s[UTF_SIZ];
  550. int charsize; /* size of utf8 char in bytes */
  551. long utf8c;
  552. int ret;
  553. /* append read bytes to unprocessed bytes */
  554. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  555. die("Couldn't read from shell: %s\n", SERRNO);
  556. /* process every complete utf8 char */
  557. buflen += ret;
  558. ptr = buf;
  559. while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
  560. charsize = utf8decode(ptr, &utf8c);
  561. utf8encode(&utf8c, s);
  562. tputc(s);
  563. ptr += charsize;
  564. buflen -= charsize;
  565. }
  566. /* keep any uncomplete utf8 char for the next call */
  567. memmove(buf, ptr, buflen);
  568. }
  569. void
  570. ttywrite(const char *s, size_t n) {
  571. if(write(cmdfd, s, n) == -1)
  572. die("write error on tty: %s\n", SERRNO);
  573. }
  574. void
  575. ttyresize(int x, int y) {
  576. struct winsize w;
  577. w.ws_row = term.row;
  578. w.ws_col = term.col;
  579. w.ws_xpixel = w.ws_ypixel = 0;
  580. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  581. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  582. }
  583. void
  584. tcursor(int mode) {
  585. static TCursor c;
  586. if(mode == CURSOR_SAVE)
  587. c = term.c;
  588. else if(mode == CURSOR_LOAD)
  589. term.c = c, tmoveto(c.x, c.y);
  590. }
  591. void
  592. treset(void) {
  593. term.c = (TCursor){{
  594. .mode = ATTR_NULL,
  595. .fg = DefaultFG,
  596. .bg = DefaultBG
  597. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  598. term.top = 0, term.bot = term.row - 1;
  599. term.mode = MODE_WRAP;
  600. tclearregion(0, 0, term.col-1, term.row-1);
  601. }
  602. void
  603. tnew(int col, int row) {
  604. /* set screen size */
  605. term.row = row, term.col = col;
  606. term.line = malloc(term.row * sizeof(Line));
  607. term.alt = malloc(term.row * sizeof(Line));
  608. for(row = 0 ; row < term.row; row++) {
  609. term.line[row] = malloc(term.col * sizeof(Glyph));
  610. term.alt [row] = malloc(term.col * sizeof(Glyph));
  611. }
  612. /* setup screen */
  613. treset();
  614. }
  615. void
  616. tswapscreen(void) {
  617. Line* tmp = term.line;
  618. term.line = term.alt;
  619. term.alt = tmp;
  620. term.mode ^= MODE_ALTSCREEN;
  621. }
  622. void
  623. tscrolldown(int orig, int n) {
  624. int i;
  625. Line temp;
  626. LIMIT(n, 0, term.bot-orig+1);
  627. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  628. for(i = term.bot; i >= orig+n; i--) {
  629. temp = term.line[i];
  630. term.line[i] = term.line[i-n];
  631. term.line[i-n] = temp;
  632. }
  633. }
  634. void
  635. tscrollup(int orig, int n) {
  636. int i;
  637. Line temp;
  638. LIMIT(n, 0, term.bot-orig+1);
  639. tclearregion(0, orig, term.col-1, orig+n-1);
  640. for(i = orig; i <= term.bot-n; i++) {
  641. temp = term.line[i];
  642. term.line[i] = term.line[i+n];
  643. term.line[i+n] = temp;
  644. }
  645. }
  646. void
  647. tnewline(int first_col) {
  648. int y = term.c.y;
  649. if(y == term.bot)
  650. tscrollup(term.top, 1);
  651. else
  652. y++;
  653. tmoveto(first_col ? 0 : term.c.x, y);
  654. }
  655. void
  656. csiparse(void) {
  657. /* int noarg = 1; */
  658. char *p = escseq.buf;
  659. escseq.narg = 0;
  660. if(*p == '?')
  661. escseq.priv = 1, p++;
  662. while(p < escseq.buf+escseq.len) {
  663. while(isdigit(*p)) {
  664. escseq.arg[escseq.narg] *= 10;
  665. escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
  666. }
  667. if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
  668. escseq.narg++, p++;
  669. else {
  670. escseq.mode = *p;
  671. escseq.narg++;
  672. return;
  673. }
  674. }
  675. }
  676. void
  677. tmoveto(int x, int y) {
  678. LIMIT(x, 0, term.col-1);
  679. LIMIT(y, 0, term.row-1);
  680. term.c.state &= ~CURSOR_WRAPNEXT;
  681. term.c.x = x;
  682. term.c.y = y;
  683. }
  684. void
  685. tsetchar(char *c) {
  686. term.line[term.c.y][term.c.x] = term.c.attr;
  687. memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
  688. term.line[term.c.y][term.c.x].state |= GLYPH_SET;
  689. }
  690. void
  691. tclearregion(int x1, int y1, int x2, int y2) {
  692. int x, y, temp;
  693. if(x1 > x2)
  694. temp = x1, x1 = x2, x2 = temp;
  695. if(y1 > y2)
  696. temp = y1, y1 = y2, y2 = temp;
  697. LIMIT(x1, 0, term.col-1);
  698. LIMIT(x2, 0, term.col-1);
  699. LIMIT(y1, 0, term.row-1);
  700. LIMIT(y2, 0, term.row-1);
  701. for(y = y1; y <= y2; y++)
  702. for(x = x1; x <= x2; x++)
  703. term.line[y][x].state = 0;
  704. }
  705. void
  706. tdeletechar(int n) {
  707. int src = term.c.x + n;
  708. int dst = term.c.x;
  709. int size = term.col - src;
  710. if(src >= term.col) {
  711. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  712. return;
  713. }
  714. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  715. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  716. }
  717. void
  718. tinsertblank(int n) {
  719. int src = term.c.x;
  720. int dst = src + n;
  721. int size = term.col - dst;
  722. if(dst >= term.col) {
  723. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  724. return;
  725. }
  726. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  727. tclearregion(src, term.c.y, dst - 1, term.c.y);
  728. }
  729. void
  730. tinsertblankline(int n) {
  731. if(term.c.y < term.top || term.c.y > term.bot)
  732. return;
  733. tscrolldown(term.c.y, n);
  734. }
  735. void
  736. tdeleteline(int n) {
  737. if(term.c.y < term.top || term.c.y > term.bot)
  738. return;
  739. tscrollup(term.c.y, n);
  740. }
  741. void
  742. tsetattr(int *attr, int l) {
  743. int i;
  744. for(i = 0; i < l; i++) {
  745. switch(attr[i]) {
  746. case 0:
  747. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
  748. term.c.attr.fg = DefaultFG;
  749. term.c.attr.bg = DefaultBG;
  750. break;
  751. case 1:
  752. term.c.attr.mode |= ATTR_BOLD;
  753. break;
  754. case 4:
  755. term.c.attr.mode |= ATTR_UNDERLINE;
  756. break;
  757. case 7:
  758. term.c.attr.mode |= ATTR_REVERSE;
  759. break;
  760. case 22:
  761. term.c.attr.mode &= ~ATTR_BOLD;
  762. break;
  763. case 24:
  764. term.c.attr.mode &= ~ATTR_UNDERLINE;
  765. break;
  766. case 27:
  767. term.c.attr.mode &= ~ATTR_REVERSE;
  768. break;
  769. case 38:
  770. if (i + 2 < l && attr[i + 1] == 5) {
  771. i += 2;
  772. if (BETWEEN(attr[i], 0, 255))
  773. term.c.attr.fg = attr[i];
  774. else
  775. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
  776. }
  777. else
  778. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
  779. break;
  780. case 39:
  781. term.c.attr.fg = DefaultFG;
  782. break;
  783. case 48:
  784. if (i + 2 < l && attr[i + 1] == 5) {
  785. i += 2;
  786. if (BETWEEN(attr[i], 0, 255))
  787. term.c.attr.bg = attr[i];
  788. else
  789. fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
  790. }
  791. else
  792. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
  793. break;
  794. case 49:
  795. term.c.attr.bg = DefaultBG;
  796. break;
  797. default:
  798. if(BETWEEN(attr[i], 30, 37))
  799. term.c.attr.fg = attr[i] - 30;
  800. else if(BETWEEN(attr[i], 40, 47))
  801. term.c.attr.bg = attr[i] - 40;
  802. else if(BETWEEN(attr[i], 90, 97))
  803. term.c.attr.fg = attr[i] - 90 + 8;
  804. else if(BETWEEN(attr[i], 100, 107))
  805. term.c.attr.fg = attr[i] - 100 + 8;
  806. else
  807. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
  808. break;
  809. }
  810. }
  811. }
  812. void
  813. tsetscroll(int t, int b) {
  814. int temp;
  815. LIMIT(t, 0, term.row-1);
  816. LIMIT(b, 0, term.row-1);
  817. if(t > b) {
  818. temp = t;
  819. t = b;
  820. b = temp;
  821. }
  822. term.top = t;
  823. term.bot = b;
  824. }
  825. void
  826. csihandle(void) {
  827. switch(escseq.mode) {
  828. default:
  829. unknown:
  830. fprintf(stderr, "erresc: unknown csi ");
  831. csidump();
  832. /* die(""); */
  833. break;
  834. case '@': /* ICH -- Insert <n> blank char */
  835. DEFAULT(escseq.arg[0], 1);
  836. tinsertblank(escseq.arg[0]);
  837. break;
  838. case 'A': /* CUU -- Cursor <n> Up */
  839. case 'e':
  840. DEFAULT(escseq.arg[0], 1);
  841. tmoveto(term.c.x, term.c.y-escseq.arg[0]);
  842. break;
  843. case 'B': /* CUD -- Cursor <n> Down */
  844. DEFAULT(escseq.arg[0], 1);
  845. tmoveto(term.c.x, term.c.y+escseq.arg[0]);
  846. break;
  847. case 'C': /* CUF -- Cursor <n> Forward */
  848. case 'a':
  849. DEFAULT(escseq.arg[0], 1);
  850. tmoveto(term.c.x+escseq.arg[0], term.c.y);
  851. break;
  852. case 'D': /* CUB -- Cursor <n> Backward */
  853. DEFAULT(escseq.arg[0], 1);
  854. tmoveto(term.c.x-escseq.arg[0], term.c.y);
  855. break;
  856. case 'E': /* CNL -- Cursor <n> Down and first col */
  857. DEFAULT(escseq.arg[0], 1);
  858. tmoveto(0, term.c.y+escseq.arg[0]);
  859. break;
  860. case 'F': /* CPL -- Cursor <n> Up and first col */
  861. DEFAULT(escseq.arg[0], 1);
  862. tmoveto(0, term.c.y-escseq.arg[0]);
  863. break;
  864. case 'G': /* CHA -- Move to <col> */
  865. case '`': /* XXX: HPA -- same? */
  866. DEFAULT(escseq.arg[0], 1);
  867. tmoveto(escseq.arg[0]-1, term.c.y);
  868. break;
  869. case 'H': /* CUP -- Move to <row> <col> */
  870. case 'f': /* XXX: HVP -- same? */
  871. DEFAULT(escseq.arg[0], 1);
  872. DEFAULT(escseq.arg[1], 1);
  873. tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
  874. break;
  875. /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
  876. case 'J': /* ED -- Clear screen */
  877. switch(escseq.arg[0]) {
  878. case 0: /* below */
  879. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  880. if(term.c.y < term.row-1)
  881. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  882. break;
  883. case 1: /* above */
  884. if(term.c.y > 1)
  885. tclearregion(0, 0, term.col-1, term.c.y-1);
  886. tclearregion(0, term.c.y, term.c.x, term.c.y);
  887. break;
  888. case 2: /* all */
  889. tclearregion(0, 0, term.col-1, term.row-1);
  890. break;
  891. default:
  892. goto unknown;
  893. }
  894. break;
  895. case 'K': /* EL -- Clear line */
  896. switch(escseq.arg[0]) {
  897. case 0: /* right */
  898. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  899. break;
  900. case 1: /* left */
  901. tclearregion(0, term.c.y, term.c.x, term.c.y);
  902. break;
  903. case 2: /* all */
  904. tclearregion(0, term.c.y, term.col-1, term.c.y);
  905. break;
  906. }
  907. break;
  908. case 'S': /* SU -- Scroll <n> line up */
  909. DEFAULT(escseq.arg[0], 1);
  910. tscrollup(term.top, escseq.arg[0]);
  911. break;
  912. case 'T': /* SD -- Scroll <n> line down */
  913. DEFAULT(escseq.arg[0], 1);
  914. tscrolldown(term.top, escseq.arg[0]);
  915. break;
  916. case 'L': /* IL -- Insert <n> blank lines */
  917. DEFAULT(escseq.arg[0], 1);
  918. tinsertblankline(escseq.arg[0]);
  919. break;
  920. case 'l': /* RM -- Reset Mode */
  921. if(escseq.priv) {
  922. switch(escseq.arg[0]) {
  923. case 1:
  924. term.mode &= ~MODE_APPKEYPAD;
  925. break;
  926. case 5: /* TODO: DECSCNM -- Remove reverse video */
  927. break;
  928. case 7:
  929. term.mode &= ~MODE_WRAP;
  930. break;
  931. case 12: /* att610 -- Stop blinking cursor (IGNORED) */
  932. break;
  933. case 20:
  934. term.mode &= ~MODE_CRLF;
  935. break;
  936. case 25:
  937. term.c.state |= CURSOR_HIDE;
  938. break;
  939. case 1049: /* = 1047 and 1048 */
  940. case 1047:
  941. if(IS_SET(MODE_ALTSCREEN)) {
  942. tclearregion(0, 0, term.col-1, term.row-1);
  943. tswapscreen();
  944. }
  945. if(escseq.arg[0] == 1047)
  946. break;
  947. case 1048:
  948. tcursor(CURSOR_LOAD);
  949. break;
  950. default:
  951. goto unknown;
  952. }
  953. } else {
  954. switch(escseq.arg[0]) {
  955. case 4:
  956. term.mode &= ~MODE_INSERT;
  957. break;
  958. default:
  959. goto unknown;
  960. }
  961. }
  962. break;
  963. case 'M': /* DL -- Delete <n> lines */
  964. DEFAULT(escseq.arg[0], 1);
  965. tdeleteline(escseq.arg[0]);
  966. break;
  967. case 'X': /* ECH -- Erase <n> char */
  968. DEFAULT(escseq.arg[0], 1);
  969. tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
  970. break;
  971. case 'P': /* DCH -- Delete <n> char */
  972. DEFAULT(escseq.arg[0], 1);
  973. tdeletechar(escseq.arg[0]);
  974. break;
  975. /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
  976. case 'd': /* VPA -- Move to <row> */
  977. DEFAULT(escseq.arg[0], 1);
  978. tmoveto(term.c.x, escseq.arg[0]-1);
  979. break;
  980. case 'h': /* SM -- Set terminal mode */
  981. if(escseq.priv) {
  982. switch(escseq.arg[0]) {
  983. case 1:
  984. term.mode |= MODE_APPKEYPAD;
  985. break;
  986. case 5: /* DECSCNM -- Reverve video */
  987. /* TODO: set REVERSE on the whole screen (f) */
  988. break;
  989. case 7:
  990. term.mode |= MODE_WRAP;
  991. break;
  992. case 20:
  993. term.mode |= MODE_CRLF;
  994. break;
  995. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  996. /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
  997. if(escseq.narg > 1 && escseq.arg[1] != 25)
  998. break;
  999. case 25:
  1000. term.c.state &= ~CURSOR_HIDE;
  1001. break;
  1002. case 1049: /* = 1047 and 1048 */
  1003. case 1047:
  1004. if(IS_SET(MODE_ALTSCREEN))
  1005. tclearregion(0, 0, term.col-1, term.row-1);
  1006. else
  1007. tswapscreen();
  1008. if(escseq.arg[0] == 1047)
  1009. break;
  1010. case 1048:
  1011. tcursor(CURSOR_SAVE);
  1012. break;
  1013. default: goto unknown;
  1014. }
  1015. } else {
  1016. switch(escseq.arg[0]) {
  1017. case 4:
  1018. term.mode |= MODE_INSERT;
  1019. break;
  1020. default: goto unknown;
  1021. }
  1022. };
  1023. break;
  1024. case 'm': /* SGR -- Terminal attribute (color) */
  1025. tsetattr(escseq.arg, escseq.narg);
  1026. break;
  1027. case 'r': /* DECSTBM -- Set Scrolling Region */
  1028. if(escseq.priv)
  1029. goto unknown;
  1030. else {
  1031. DEFAULT(escseq.arg[0], 1);
  1032. DEFAULT(escseq.arg[1], term.row);
  1033. tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
  1034. tmoveto(0, 0);
  1035. }
  1036. break;
  1037. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1038. tcursor(CURSOR_SAVE);
  1039. break;
  1040. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1041. tcursor(CURSOR_LOAD);
  1042. break;
  1043. }
  1044. }
  1045. void
  1046. csidump(void) {
  1047. int i;
  1048. printf("ESC [ %s", escseq.priv ? "? " : "");
  1049. if(escseq.narg)
  1050. for(i = 0; i < escseq.narg; i++)
  1051. printf("%d ", escseq.arg[i]);
  1052. if(escseq.mode)
  1053. putchar(escseq.mode);
  1054. putchar('\n');
  1055. }
  1056. void
  1057. csireset(void) {
  1058. memset(&escseq, 0, sizeof(escseq));
  1059. }
  1060. void
  1061. tputtab(void) {
  1062. int space = TAB - term.c.x % TAB;
  1063. tmoveto(term.c.x + space, term.c.y);
  1064. }
  1065. void
  1066. tputc(char *c) {
  1067. char ascii = *c;
  1068. if(term.esc & ESC_START) {
  1069. if(term.esc & ESC_CSI) {
  1070. escseq.buf[escseq.len++] = ascii;
  1071. if(BETWEEN(ascii, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
  1072. term.esc = 0;
  1073. csiparse(), csihandle();
  1074. }
  1075. /* TODO: handle other OSC */
  1076. } else if(term.esc & ESC_OSC) {
  1077. if(ascii == ';') {
  1078. term.titlelen = 0;
  1079. term.esc = ESC_START | ESC_TITLE;
  1080. }
  1081. } else if(term.esc & ESC_TITLE) {
  1082. if(ascii == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
  1083. term.esc = 0;
  1084. term.title[term.titlelen] = '\0';
  1085. XStoreName(xw.dpy, xw.win, term.title);
  1086. } else {
  1087. term.title[term.titlelen++] = ascii;
  1088. }
  1089. } else if(term.esc & ESC_ALTCHARSET) {
  1090. switch(ascii) {
  1091. case '0': /* Line drawing crap */
  1092. term.c.attr.mode |= ATTR_GFX;
  1093. break;
  1094. case 'B': /* Back to regular text */
  1095. term.c.attr.mode &= ~ATTR_GFX;
  1096. break;
  1097. default:
  1098. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1099. }
  1100. term.esc = 0;
  1101. } else {
  1102. switch(ascii) {
  1103. case '[':
  1104. term.esc |= ESC_CSI;
  1105. break;
  1106. case ']':
  1107. term.esc |= ESC_OSC;
  1108. break;
  1109. case '(':
  1110. term.esc |= ESC_ALTCHARSET;
  1111. break;
  1112. case 'D': /* IND -- Linefeed */
  1113. if(term.c.y == term.bot)
  1114. tscrollup(term.top, 1);
  1115. else
  1116. tmoveto(term.c.x, term.c.y+1);
  1117. term.esc = 0;
  1118. break;
  1119. case 'E': /* NEL -- Next line */
  1120. tnewline(1); /* always go to first col */
  1121. term.esc = 0;
  1122. break;
  1123. case 'M': /* RI -- Reverse index */
  1124. if(term.c.y == term.top)
  1125. tscrolldown(term.top, 1);
  1126. else
  1127. tmoveto(term.c.x, term.c.y-1);
  1128. term.esc = 0;
  1129. break;
  1130. case 'c': /* RIS -- Reset to inital state */
  1131. treset();
  1132. term.esc = 0;
  1133. break;
  1134. case '=': /* DECPAM -- Application keypad */
  1135. term.mode |= MODE_APPKEYPAD;
  1136. term.esc = 0;
  1137. break;
  1138. case '>': /* DECPNM -- Normal keypad */
  1139. term.mode &= ~MODE_APPKEYPAD;
  1140. term.esc = 0;
  1141. break;
  1142. case '7': /* DECSC -- Save Cursor */
  1143. tcursor(CURSOR_SAVE);
  1144. term.esc = 0;
  1145. break;
  1146. case '8': /* DECRC -- Restore Cursor */
  1147. tcursor(CURSOR_LOAD);
  1148. term.esc = 0;
  1149. break;
  1150. default:
  1151. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1152. (unsigned char) ascii, isprint(ascii)?ascii:'.');
  1153. term.esc = 0;
  1154. }
  1155. }
  1156. } else {
  1157. switch(ascii) {
  1158. case '\t':
  1159. tputtab();
  1160. break;
  1161. case '\b':
  1162. tmoveto(term.c.x-1, term.c.y);
  1163. break;
  1164. case '\r':
  1165. tmoveto(0, term.c.y);
  1166. break;
  1167. case '\f':
  1168. case '\v':
  1169. case '\n':
  1170. /* go to first col if the mode is set */
  1171. tnewline(IS_SET(MODE_CRLF));
  1172. break;
  1173. case '\a':
  1174. if(!(xw.state & WIN_FOCUSED))
  1175. xseturgency(1);
  1176. break;
  1177. case '\033':
  1178. csireset();
  1179. term.esc = ESC_START;
  1180. break;
  1181. default:
  1182. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1183. tnewline(1); /* always go to first col */
  1184. tsetchar(c);
  1185. if(term.c.x+1 < term.col)
  1186. tmoveto(term.c.x+1, term.c.y);
  1187. else
  1188. term.c.state |= CURSOR_WRAPNEXT;
  1189. break;
  1190. }
  1191. }
  1192. }
  1193. int
  1194. tresize(int col, int row) {
  1195. int i, x;
  1196. int minrow = MIN(row, term.row);
  1197. int mincol = MIN(col, term.col);
  1198. int slide = term.c.y - row + 1;
  1199. if(col < 1 || row < 1)
  1200. return 0;
  1201. /* free unneeded rows */
  1202. i = 0;
  1203. if(slide > 0) {
  1204. /* slide screen to keep cursor where we expect it -
  1205. * tscrollup would work here, but we can optimize to
  1206. * memmove because we're freeing the earlier lines */
  1207. for(/* i = 0 */; i < slide; i++) {
  1208. free(term.line[i]);
  1209. free(term.alt[i]);
  1210. }
  1211. memmove(term.line, term.line + slide, row * sizeof(Line));
  1212. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1213. }
  1214. for(i += row; i < term.row; i++) {
  1215. free(term.line[i]);
  1216. free(term.alt[i]);
  1217. }
  1218. /* resize to new height */
  1219. term.line = realloc(term.line, row * sizeof(Line));
  1220. term.alt = realloc(term.alt, row * sizeof(Line));
  1221. /* resize each row to new width, zero-pad if needed */
  1222. for(i = 0; i < minrow; i++) {
  1223. term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
  1224. term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
  1225. for(x = mincol; x < col; x++) {
  1226. term.line[i][x].state = 0;
  1227. term.alt[i][x].state = 0;
  1228. }
  1229. }
  1230. /* allocate any new rows */
  1231. for(/* i == minrow */; i < row; i++) {
  1232. term.line[i] = calloc(col, sizeof(Glyph));
  1233. term.alt [i] = calloc(col, sizeof(Glyph));
  1234. }
  1235. /* update terminal size */
  1236. term.col = col, term.row = row;
  1237. /* make use of the LIMIT in tmoveto */
  1238. tmoveto(term.c.x, term.c.y);
  1239. /* reset scrolling region */
  1240. tsetscroll(0, row-1);
  1241. return (slide > 0);
  1242. }
  1243. void
  1244. xresize(int col, int row) {
  1245. Pixmap newbuf;
  1246. int oldw, oldh;
  1247. oldw = xw.bufw;
  1248. oldh = xw.bufh;
  1249. xw.bufw = MAX(1, col * xw.cw);
  1250. xw.bufh = MAX(1, row * xw.ch);
  1251. newbuf = XCreatePixmap(xw.dpy, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dpy, xw.scr));
  1252. XCopyArea(xw.dpy, xw.buf, newbuf, dc.gc, 0, 0, xw.bufw, xw.bufh, 0, 0);
  1253. XFreePixmap(xw.dpy, xw.buf);
  1254. XSetForeground(xw.dpy, dc.gc, dc.col[DefaultBG]);
  1255. if(xw.bufw > oldw)
  1256. XFillRectangle(xw.dpy, newbuf, dc.gc, oldw, 0,
  1257. xw.bufw-oldw, MIN(xw.bufh, oldh));
  1258. else if(xw.bufw < oldw && (BORDER > 0 || xw.w > xw.bufw))
  1259. XClearArea(xw.dpy, xw.win, BORDER+xw.bufw, BORDER,
  1260. xw.w-xw.bufh-BORDER, BORDER+MIN(xw.bufh, oldh),
  1261. False);
  1262. if(xw.bufh > oldh)
  1263. XFillRectangle(xw.dpy, newbuf, dc.gc, 0, oldh,
  1264. xw.bufw, xw.bufh-oldh);
  1265. else if(xw.bufh < oldh && (BORDER > 0 || xw.h > xw.bufh))
  1266. XClearArea(xw.dpy, xw.win, BORDER, BORDER+xw.bufh,
  1267. xw.w-2*BORDER, xw.h-xw.bufh-BORDER,
  1268. False);
  1269. xw.buf = newbuf;
  1270. }
  1271. void
  1272. xloadcols(void) {
  1273. int i, r, g, b;
  1274. XColor color;
  1275. unsigned long white = WhitePixel(xw.dpy, xw.scr);
  1276. for(i = 0; i < 16; i++) {
  1277. if (!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
  1278. dc.col[i] = white;
  1279. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1280. } else
  1281. dc.col[i] = color.pixel;
  1282. }
  1283. /* same colors as xterm */
  1284. for(r = 0; r < 6; r++)
  1285. for(g = 0; g < 6; g++)
  1286. for(b = 0; b < 6; b++) {
  1287. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1288. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1289. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1290. if (!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1291. dc.col[i] = white;
  1292. fprintf(stderr, "Could not allocate color %d\n", i);
  1293. } else
  1294. dc.col[i] = color.pixel;
  1295. i++;
  1296. }
  1297. for(r = 0; r < 24; r++, i++) {
  1298. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1299. if (!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1300. dc.col[i] = white;
  1301. fprintf(stderr, "Could not allocate color %d\n", i);
  1302. } else
  1303. dc.col[i] = color.pixel;
  1304. }
  1305. }
  1306. void
  1307. xclear(int x1, int y1, int x2, int y2) {
  1308. XSetForeground(xw.dpy, dc.gc, dc.col[DefaultBG]);
  1309. XFillRectangle(xw.dpy, xw.buf, dc.gc,
  1310. x1 * xw.cw, y1 * xw.ch,
  1311. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1312. }
  1313. void
  1314. xhints(void)
  1315. {
  1316. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1317. XWMHints wm = {.flags = InputHint, .input = 1};
  1318. XSizeHints size = {
  1319. .flags = PSize | PResizeInc | PBaseSize,
  1320. .height = xw.h,
  1321. .width = xw.w,
  1322. .height_inc = xw.ch,
  1323. .width_inc = xw.cw,
  1324. .base_height = 2*BORDER,
  1325. .base_width = 2*BORDER,
  1326. };
  1327. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
  1328. }
  1329. XFontSet
  1330. xinitfont(char *fontstr)
  1331. {
  1332. XFontSet set;
  1333. char *def, **missing;
  1334. int n;
  1335. missing = NULL;
  1336. set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
  1337. if(missing) {
  1338. while(n--)
  1339. fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
  1340. XFreeStringList(missing);
  1341. }
  1342. return set;
  1343. }
  1344. void
  1345. xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing)
  1346. {
  1347. XFontStruct **xfonts;
  1348. char **font_names;
  1349. int i, n;
  1350. *ascent = *descent = *lbearing = *rbearing = 0;
  1351. n = XFontsOfFontSet(set, &xfonts, &font_names);
  1352. for(i = 0; i < n; i++) {
  1353. *ascent = MAX(*ascent, (*xfonts)->ascent);
  1354. *descent = MAX(*descent, (*xfonts)->descent);
  1355. *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
  1356. *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
  1357. xfonts++;
  1358. }
  1359. }
  1360. void
  1361. initfonts(char *fontstr, char *bfontstr)
  1362. {
  1363. if((dc.font.set = xinitfont(fontstr)) == NULL ||
  1364. (dc.bfont.set = xinitfont(bfontstr)) == NULL)
  1365. die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
  1366. xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
  1367. &dc.font.lbearing, &dc.font.rbearing);
  1368. xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
  1369. &dc.bfont.lbearing, &dc.bfont.rbearing);
  1370. }
  1371. void
  1372. xinit(void) {
  1373. XSetWindowAttributes attrs;
  1374. Cursor cursor;
  1375. if(!(xw.dpy = XOpenDisplay(NULL)))
  1376. die("Can't open display\n");
  1377. xw.scr = XDefaultScreen(xw.dpy);
  1378. /* font */
  1379. initfonts(FONT, BOLDFONT);
  1380. /* XXX: Assuming same size for bold font */
  1381. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1382. xw.ch = dc.font.ascent + dc.font.descent;
  1383. /* colors */
  1384. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1385. xloadcols();
  1386. /* window - default size */
  1387. xw.bufh = 24 * xw.ch;
  1388. xw.bufw = 80 * xw.cw;
  1389. xw.h = xw.bufh + 2*BORDER;
  1390. xw.w = xw.bufw + 2*BORDER;
  1391. attrs.background_pixel = dc.col[DefaultBG];
  1392. attrs.border_pixel = dc.col[DefaultBG];
  1393. attrs.bit_gravity = NorthWestGravity;
  1394. attrs.event_mask = FocusChangeMask | KeyPressMask
  1395. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1396. | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
  1397. attrs.colormap = xw.cmap;
  1398. xw.win = XCreateWindow(xw.dpy, XRootWindow(xw.dpy, xw.scr), 0, 0,
  1399. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1400. XDefaultVisual(xw.dpy, xw.scr),
  1401. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1402. | CWColormap,
  1403. &attrs);
  1404. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dpy, xw.scr));
  1405. /* input methods */
  1406. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1407. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1408. | XIMStatusNothing, XNClientWindow, xw.win,
  1409. XNFocusWindow, xw.win, NULL);
  1410. /* gc */
  1411. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1412. /* white cursor, black outline */
  1413. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1414. XDefineCursor(xw.dpy, xw.win, cursor);
  1415. XRecolorCursor(xw.dpy, cursor,
  1416. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1417. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1418. XMapWindow(xw.dpy, xw.win);
  1419. xhints();
  1420. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1421. XSync(xw.dpy, 0);
  1422. }
  1423. void
  1424. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1425. unsigned long xfg, xbg;
  1426. int winx = x*xw.cw, winy = y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1427. int i;
  1428. if(base.mode & ATTR_REVERSE)
  1429. xfg = dc.col[base.bg], xbg = dc.col[base.fg];
  1430. else
  1431. xfg = dc.col[base.fg], xbg = dc.col[base.bg];
  1432. XSetBackground(xw.dpy, dc.gc, xbg);
  1433. XSetForeground(xw.dpy, dc.gc, xfg);
  1434. if(base.mode & ATTR_GFX) {
  1435. for(i = 0; i < bytelen; i++) {
  1436. char c = gfx[(unsigned int)s[i] % 256];
  1437. if(c)
  1438. s[i] = c;
  1439. else if(s[i] > 0x5f)
  1440. s[i] -= 0x5f;
  1441. }
  1442. }
  1443. XmbDrawImageString(xw.dpy, xw.buf, base.mode & ATTR_BOLD ? dc.bfont.set : dc.font.set,
  1444. dc.gc, winx, winy, s, bytelen);
  1445. if(base.mode & ATTR_UNDERLINE)
  1446. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1447. }
  1448. void
  1449. xdrawcursor(void) {
  1450. static int oldx = 0;
  1451. static int oldy = 0;
  1452. int sl;
  1453. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1454. LIMIT(oldx, 0, term.col-1);
  1455. LIMIT(oldy, 0, term.row-1);
  1456. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1457. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1458. /* remove the old cursor */
  1459. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1460. sl = utf8size(term.line[oldy][oldx].c);
  1461. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1462. } else
  1463. xclear(oldx, oldy, oldx, oldy);
  1464. /* draw the new one */
  1465. if(!(term.c.state & CURSOR_HIDE) && (xw.state & WIN_FOCUSED)) {
  1466. sl = utf8size(g.c);
  1467. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1468. oldx = term.c.x, oldy = term.c.y;
  1469. }
  1470. }
  1471. #ifdef DEBUG
  1472. /* basic drawing routines */
  1473. void
  1474. xdrawc(int x, int y, Glyph g) {
  1475. int sl = utf8size(g.c);
  1476. XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
  1477. XSetBackground(xw.dpy, dc.gc, dc.col[g.bg]);
  1478. XSetForeground(xw.dpy, dc.gc, dc.col[g.fg]);
  1479. XmbDrawImageString(xw.dpy, xw.buf, g.mode&ATTR_BOLD?dc.bfont.fs:dc.font.fs,
  1480. dc.gc, r.x, r.y+dc.font.ascent, g.c, sl);
  1481. }
  1482. void
  1483. draw(int dummy) {
  1484. int x, y;
  1485. xclear(0, 0, term.col-1, term.row-1);
  1486. for(y = 0; y < term.row; y++)
  1487. for(x = 0; x < term.col; x++)
  1488. if(term.line[y][x].state & GLYPH_SET)
  1489. xdrawc(x, y, term.line[y][x]);
  1490. xdrawcursor();
  1491. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1492. XFlush(xw.dpy);
  1493. }
  1494. #else
  1495. /* optimized drawing routine */
  1496. void
  1497. draw(int redraw_all) {
  1498. int ic, ib, x, y, ox, sl;
  1499. Glyph base, new;
  1500. char buf[DRAW_BUF_SIZ];
  1501. if(!(xw.state & WIN_VISIBLE))
  1502. return;
  1503. xclear(0, 0, term.col-1, term.row-1);
  1504. for(y = 0; y < term.row; y++) {
  1505. base = term.line[y][0];
  1506. ic = ib = ox = 0;
  1507. for(x = 0; x < term.col; x++) {
  1508. new = term.line[y][x];
  1509. if(sel.bx!=-1 && *(new.c) && selected(x, y))
  1510. new.mode ^= ATTR_REVERSE;
  1511. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1512. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1513. xdraws(buf, base, ox, y, ic, ib);
  1514. ic = ib = 0;
  1515. }
  1516. if(new.state & GLYPH_SET) {
  1517. if(ib == 0) {
  1518. ox = x;
  1519. base = new;
  1520. }
  1521. sl = utf8size(new.c);
  1522. memcpy(buf+ib, new.c, sl);
  1523. ib += sl;
  1524. ++ic;
  1525. }
  1526. }
  1527. if(ib > 0)
  1528. xdraws(buf, base, ox, y, ic, ib);
  1529. }
  1530. xdrawcursor();
  1531. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1532. }
  1533. #endif
  1534. void
  1535. expose(XEvent *ev) {
  1536. XExposeEvent *e = &ev->xexpose;
  1537. if(xw.state & WIN_REDRAW) {
  1538. if(!e->count) {
  1539. xw.state &= ~WIN_REDRAW;
  1540. draw(SCREEN_REDRAW);
  1541. }
  1542. } else
  1543. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
  1544. e->width, e->height, e->x, e->y);
  1545. }
  1546. void
  1547. visibility(XEvent *ev) {
  1548. XVisibilityEvent *e = &ev->xvisibility;
  1549. if(e->state == VisibilityFullyObscured)
  1550. xw.state &= ~WIN_VISIBLE;
  1551. else if(!(xw.state & WIN_VISIBLE))
  1552. /* need a full redraw for next Expose, not just a buf copy */
  1553. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1554. }
  1555. void
  1556. unmap(XEvent *ev) {
  1557. xw.state &= ~WIN_VISIBLE;
  1558. }
  1559. void
  1560. xseturgency(int add) {
  1561. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1562. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1563. XSetWMHints(xw.dpy, xw.win, h);
  1564. XFree(h);
  1565. }
  1566. void
  1567. focus(XEvent *ev) {
  1568. if(ev->type == FocusIn) {
  1569. xw.state |= WIN_FOCUSED;
  1570. xseturgency(0);
  1571. } else
  1572. xw.state &= ~WIN_FOCUSED;
  1573. draw(SCREEN_UPDATE);
  1574. }
  1575. char*
  1576. kmap(KeySym k) {
  1577. int i;
  1578. for(i = 0; i < LEN(key); i++)
  1579. if(key[i].k == k)
  1580. return (char*)key[i].s;
  1581. return NULL;
  1582. }
  1583. void
  1584. kpress(XEvent *ev) {
  1585. XKeyEvent *e = &ev->xkey;
  1586. KeySym ksym;
  1587. char buf[32];
  1588. char *customkey;
  1589. int len;
  1590. int meta;
  1591. int shift;
  1592. Status status;
  1593. meta = e->state & Mod1Mask;
  1594. shift = e->state & ShiftMask;
  1595. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1596. /* 1. custom keys from config.h */
  1597. if((customkey = kmap(ksym)))
  1598. ttywrite(customkey, strlen(customkey));
  1599. /* 2. hardcoded (overrides X lookup) */
  1600. else
  1601. switch(ksym) {
  1602. case XK_Up:
  1603. case XK_Down:
  1604. case XK_Left:
  1605. case XK_Right:
  1606. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
  1607. ttywrite(buf, 3);
  1608. break;
  1609. case XK_Insert:
  1610. if(shift)
  1611. selpaste();
  1612. break;
  1613. case XK_Return:
  1614. if(IS_SET(MODE_CRLF))
  1615. ttywrite("\r\n", 2);
  1616. else
  1617. ttywrite("\r", 1);
  1618. break;
  1619. /* 3. X lookup */
  1620. default:
  1621. if(len > 0) {
  1622. if(meta && len == 1)
  1623. ttywrite("\033", 1);
  1624. ttywrite(buf, len);
  1625. }
  1626. break;
  1627. }
  1628. }
  1629. void
  1630. resize(XEvent *e) {
  1631. int col, row;
  1632. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  1633. return;
  1634. xw.w = e->xconfigure.width;
  1635. xw.h = e->xconfigure.height;
  1636. col = (xw.w - 2*BORDER) / xw.cw;
  1637. row = (xw.h - 2*BORDER) / xw.ch;
  1638. if(col == term.col && row == term.row)
  1639. return;
  1640. if(tresize(col, row))
  1641. draw(SCREEN_REDRAW);
  1642. ttyresize(col, row);
  1643. xresize(col, row);
  1644. }
  1645. void
  1646. run(void) {
  1647. XEvent ev;
  1648. fd_set rfd;
  1649. int xfd = XConnectionNumber(xw.dpy);
  1650. for(;;) {
  1651. FD_ZERO(&rfd);
  1652. FD_SET(cmdfd, &rfd);
  1653. FD_SET(xfd, &rfd);
  1654. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
  1655. if(errno == EINTR)
  1656. continue;
  1657. die("select failed: %s\n", SERRNO);
  1658. }
  1659. if(FD_ISSET(cmdfd, &rfd)) {
  1660. ttyread();
  1661. draw(SCREEN_UPDATE);
  1662. }
  1663. while(XPending(xw.dpy)) {
  1664. XNextEvent(xw.dpy, &ev);
  1665. if (XFilterEvent(&ev, xw.win))
  1666. continue;
  1667. if(handler[ev.type])
  1668. (handler[ev.type])(&ev);
  1669. }
  1670. }
  1671. }
  1672. int
  1673. main(int argc, char *argv[]) {
  1674. int i;
  1675. for(i = 1; i < argc; i++) {
  1676. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  1677. case 't':
  1678. if(++i < argc) opt_title = argv[i];
  1679. break;
  1680. case 'c':
  1681. if(++i < argc) opt_class = argv[i];
  1682. break;
  1683. case 'e':
  1684. if(++i < argc) opt_cmd = &argv[i];
  1685. break;
  1686. case 'v':
  1687. default:
  1688. die(USAGE);
  1689. }
  1690. /* -e eats every remaining arguments */
  1691. if(opt_cmd)
  1692. break;
  1693. }
  1694. setlocale(LC_CTYPE, "");
  1695. tnew(80, 24);
  1696. ttynew();
  1697. xinit();
  1698. selinit();
  1699. run();
  1700. return 0;
  1701. }