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.

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