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.

1861 lines
42 KiB

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
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
15 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* dis;
  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.dis, 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.dis, 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.dis, "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.dis, XA_PRIMARY, xw.win, CurrentTime);
  451. clipboard = XInternAtom(xw.dis, "CLIPBOARD", 0);
  452. XSetSelectionOwner(xw.dis, clipboard, xw.win, CurrentTime);
  453. XFlush(xw.dis);
  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. char buf[BUFSIZ], *ptr;
  546. char s[UTF_SIZ];
  547. int ret, br;
  548. static int buflen = 0;
  549. long u;
  550. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  551. die("Couldn't read from shell: %s\n", SERRNO);
  552. else {
  553. buflen += ret;
  554. for(ptr=buf; buflen>=UTF_SIZ||isfullutf8(ptr,buflen); buflen-=br) {
  555. br = utf8decode(ptr, &u);
  556. utf8encode(&u, s);
  557. tputc(s);
  558. ptr += br;
  559. }
  560. memcpy(buf, ptr, buflen);
  561. }
  562. }
  563. void
  564. ttywrite(const char *s, size_t n) {
  565. if(write(cmdfd, s, n) == -1)
  566. die("write error on tty: %s\n", SERRNO);
  567. }
  568. void
  569. ttyresize(int x, int y) {
  570. struct winsize w;
  571. w.ws_row = term.row;
  572. w.ws_col = term.col;
  573. w.ws_xpixel = w.ws_ypixel = 0;
  574. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  575. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  576. }
  577. void
  578. tcursor(int mode) {
  579. static TCursor c;
  580. if(mode == CURSOR_SAVE)
  581. c = term.c;
  582. else if(mode == CURSOR_LOAD)
  583. term.c = c, tmoveto(c.x, c.y);
  584. }
  585. void
  586. treset(void) {
  587. term.c = (TCursor){{
  588. .mode = ATTR_NULL,
  589. .fg = DefaultFG,
  590. .bg = DefaultBG
  591. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  592. term.top = 0, term.bot = term.row - 1;
  593. term.mode = MODE_WRAP;
  594. tclearregion(0, 0, term.col-1, term.row-1);
  595. }
  596. void
  597. tnew(int col, int row) {
  598. /* set screen size */
  599. term.row = row, term.col = col;
  600. term.line = malloc(term.row * sizeof(Line));
  601. term.alt = malloc(term.row * sizeof(Line));
  602. for(row = 0 ; row < term.row; row++) {
  603. term.line[row] = malloc(term.col * sizeof(Glyph));
  604. term.alt [row] = malloc(term.col * sizeof(Glyph));
  605. }
  606. /* setup screen */
  607. treset();
  608. }
  609. void
  610. tswapscreen(void) {
  611. Line* tmp = term.line;
  612. term.line = term.alt;
  613. term.alt = tmp;
  614. term.mode ^= MODE_ALTSCREEN;
  615. }
  616. void
  617. tscrolldown(int orig, int n) {
  618. int i;
  619. Line temp;
  620. LIMIT(n, 0, term.bot-orig+1);
  621. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  622. for(i = term.bot; i >= orig+n; i--) {
  623. temp = term.line[i];
  624. term.line[i] = term.line[i-n];
  625. term.line[i-n] = temp;
  626. }
  627. }
  628. void
  629. tscrollup(int orig, int n) {
  630. int i;
  631. Line temp;
  632. LIMIT(n, 0, term.bot-orig+1);
  633. tclearregion(0, orig, term.col-1, orig+n-1);
  634. for(i = orig; i <= term.bot-n; i++) {
  635. temp = term.line[i];
  636. term.line[i] = term.line[i+n];
  637. term.line[i+n] = temp;
  638. }
  639. }
  640. void
  641. tnewline(int first_col) {
  642. int y = term.c.y;
  643. if(y == term.bot)
  644. tscrollup(term.top, 1);
  645. else
  646. y++;
  647. tmoveto(first_col ? 0 : term.c.x, y);
  648. }
  649. void
  650. csiparse(void) {
  651. /* int noarg = 1; */
  652. char *p = escseq.buf;
  653. escseq.narg = 0;
  654. if(*p == '?')
  655. escseq.priv = 1, p++;
  656. while(p < escseq.buf+escseq.len) {
  657. while(isdigit(*p)) {
  658. escseq.arg[escseq.narg] *= 10;
  659. escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
  660. }
  661. if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
  662. escseq.narg++, p++;
  663. else {
  664. escseq.mode = *p;
  665. escseq.narg++;
  666. return;
  667. }
  668. }
  669. }
  670. void
  671. tmoveto(int x, int y) {
  672. LIMIT(x, 0, term.col-1);
  673. LIMIT(y, 0, term.row-1);
  674. term.c.state &= ~CURSOR_WRAPNEXT;
  675. term.c.x = x;
  676. term.c.y = y;
  677. }
  678. void
  679. tsetchar(char *c) {
  680. term.line[term.c.y][term.c.x] = term.c.attr;
  681. memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
  682. term.line[term.c.y][term.c.x].state |= GLYPH_SET;
  683. }
  684. void
  685. tclearregion(int x1, int y1, int x2, int y2) {
  686. int x, y, temp;
  687. if(x1 > x2)
  688. temp = x1, x1 = x2, x2 = temp;
  689. if(y1 > y2)
  690. temp = y1, y1 = y2, y2 = temp;
  691. LIMIT(x1, 0, term.col-1);
  692. LIMIT(x2, 0, term.col-1);
  693. LIMIT(y1, 0, term.row-1);
  694. LIMIT(y2, 0, term.row-1);
  695. for(y = y1; y <= y2; y++)
  696. for(x = x1; x <= x2; x++)
  697. term.line[y][x].state = 0;
  698. }
  699. void
  700. tdeletechar(int n) {
  701. int src = term.c.x + n;
  702. int dst = term.c.x;
  703. int size = term.col - src;
  704. if(src >= term.col) {
  705. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  706. return;
  707. }
  708. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  709. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  710. }
  711. void
  712. tinsertblank(int n) {
  713. int src = term.c.x;
  714. int dst = src + n;
  715. int size = term.col - dst;
  716. if(dst >= term.col) {
  717. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  718. return;
  719. }
  720. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  721. tclearregion(src, term.c.y, dst - 1, term.c.y);
  722. }
  723. void
  724. tinsertblankline(int n) {
  725. if(term.c.y < term.top || term.c.y > term.bot)
  726. return;
  727. tscrolldown(term.c.y, n);
  728. }
  729. void
  730. tdeleteline(int n) {
  731. if(term.c.y < term.top || term.c.y > term.bot)
  732. return;
  733. tscrollup(term.c.y, n);
  734. }
  735. void
  736. tsetattr(int *attr, int l) {
  737. int i;
  738. for(i = 0; i < l; i++) {
  739. switch(attr[i]) {
  740. case 0:
  741. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
  742. term.c.attr.fg = DefaultFG;
  743. term.c.attr.bg = DefaultBG;
  744. break;
  745. case 1:
  746. term.c.attr.mode |= ATTR_BOLD;
  747. break;
  748. case 4:
  749. term.c.attr.mode |= ATTR_UNDERLINE;
  750. break;
  751. case 7:
  752. term.c.attr.mode |= ATTR_REVERSE;
  753. break;
  754. case 22:
  755. term.c.attr.mode &= ~ATTR_BOLD;
  756. break;
  757. case 24:
  758. term.c.attr.mode &= ~ATTR_UNDERLINE;
  759. break;
  760. case 27:
  761. term.c.attr.mode &= ~ATTR_REVERSE;
  762. break;
  763. case 38:
  764. if (i + 2 < l && attr[i + 1] == 5) {
  765. i += 2;
  766. if (BETWEEN(attr[i], 0, 255))
  767. term.c.attr.fg = attr[i];
  768. else
  769. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
  770. }
  771. else
  772. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
  773. break;
  774. case 39:
  775. term.c.attr.fg = DefaultFG;
  776. break;
  777. case 48:
  778. if (i + 2 < l && attr[i + 1] == 5) {
  779. i += 2;
  780. if (BETWEEN(attr[i], 0, 255))
  781. term.c.attr.bg = attr[i];
  782. else
  783. fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
  784. }
  785. else
  786. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
  787. break;
  788. case 49:
  789. term.c.attr.bg = DefaultBG;
  790. break;
  791. default:
  792. if(BETWEEN(attr[i], 30, 37))
  793. term.c.attr.fg = attr[i] - 30;
  794. else if(BETWEEN(attr[i], 40, 47))
  795. term.c.attr.bg = attr[i] - 40;
  796. else if(BETWEEN(attr[i], 90, 97))
  797. term.c.attr.fg = attr[i] - 90 + 8;
  798. else if(BETWEEN(attr[i], 100, 107))
  799. term.c.attr.fg = attr[i] - 100 + 8;
  800. else
  801. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
  802. break;
  803. }
  804. }
  805. }
  806. void
  807. tsetscroll(int t, int b) {
  808. int temp;
  809. LIMIT(t, 0, term.row-1);
  810. LIMIT(b, 0, term.row-1);
  811. if(t > b) {
  812. temp = t;
  813. t = b;
  814. b = temp;
  815. }
  816. term.top = t;
  817. term.bot = b;
  818. }
  819. void
  820. csihandle(void) {
  821. switch(escseq.mode) {
  822. default:
  823. unknown:
  824. printf("erresc: unknown csi ");
  825. csidump();
  826. /* die(""); */
  827. break;
  828. case '@': /* ICH -- Insert <n> blank char */
  829. DEFAULT(escseq.arg[0], 1);
  830. tinsertblank(escseq.arg[0]);
  831. break;
  832. case 'A': /* CUU -- Cursor <n> Up */
  833. case 'e':
  834. DEFAULT(escseq.arg[0], 1);
  835. tmoveto(term.c.x, term.c.y-escseq.arg[0]);
  836. break;
  837. case 'B': /* CUD -- Cursor <n> Down */
  838. DEFAULT(escseq.arg[0], 1);
  839. tmoveto(term.c.x, term.c.y+escseq.arg[0]);
  840. break;
  841. case 'C': /* CUF -- Cursor <n> Forward */
  842. case 'a':
  843. DEFAULT(escseq.arg[0], 1);
  844. tmoveto(term.c.x+escseq.arg[0], term.c.y);
  845. break;
  846. case 'D': /* CUB -- Cursor <n> Backward */
  847. DEFAULT(escseq.arg[0], 1);
  848. tmoveto(term.c.x-escseq.arg[0], term.c.y);
  849. break;
  850. case 'E': /* CNL -- Cursor <n> Down and first col */
  851. DEFAULT(escseq.arg[0], 1);
  852. tmoveto(0, term.c.y+escseq.arg[0]);
  853. break;
  854. case 'F': /* CPL -- Cursor <n> Up and first col */
  855. DEFAULT(escseq.arg[0], 1);
  856. tmoveto(0, term.c.y-escseq.arg[0]);
  857. break;
  858. case 'G': /* CHA -- Move to <col> */
  859. case '`': /* XXX: HPA -- same? */
  860. DEFAULT(escseq.arg[0], 1);
  861. tmoveto(escseq.arg[0]-1, term.c.y);
  862. break;
  863. case 'H': /* CUP -- Move to <row> <col> */
  864. case 'f': /* XXX: HVP -- same? */
  865. DEFAULT(escseq.arg[0], 1);
  866. DEFAULT(escseq.arg[1], 1);
  867. tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
  868. break;
  869. /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
  870. case 'J': /* ED -- Clear screen */
  871. switch(escseq.arg[0]) {
  872. case 0: /* below */
  873. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  874. if(term.c.y < term.row-1)
  875. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  876. break;
  877. case 1: /* above */
  878. if(term.c.y > 1)
  879. tclearregion(0, 0, term.col-1, term.c.y-1);
  880. tclearregion(0, term.c.y, term.c.x, term.c.y);
  881. break;
  882. case 2: /* all */
  883. tclearregion(0, 0, term.col-1, term.row-1);
  884. break;
  885. default:
  886. goto unknown;
  887. }
  888. break;
  889. case 'K': /* EL -- Clear line */
  890. switch(escseq.arg[0]) {
  891. case 0: /* right */
  892. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  893. break;
  894. case 1: /* left */
  895. tclearregion(0, term.c.y, term.c.x, term.c.y);
  896. break;
  897. case 2: /* all */
  898. tclearregion(0, term.c.y, term.col-1, term.c.y);
  899. break;
  900. }
  901. break;
  902. case 'S': /* SU -- Scroll <n> line up */
  903. DEFAULT(escseq.arg[0], 1);
  904. tscrollup(term.top, escseq.arg[0]);
  905. break;
  906. case 'T': /* SD -- Scroll <n> line down */
  907. DEFAULT(escseq.arg[0], 1);
  908. tscrolldown(term.top, escseq.arg[0]);
  909. break;
  910. case 'L': /* IL -- Insert <n> blank lines */
  911. DEFAULT(escseq.arg[0], 1);
  912. tinsertblankline(escseq.arg[0]);
  913. break;
  914. case 'l': /* RM -- Reset Mode */
  915. if(escseq.priv) {
  916. switch(escseq.arg[0]) {
  917. case 1:
  918. term.mode &= ~MODE_APPKEYPAD;
  919. break;
  920. case 5: /* TODO: DECSCNM -- Remove reverse video */
  921. break;
  922. case 7:
  923. term.mode &= ~MODE_WRAP;
  924. break;
  925. case 12: /* att610 -- Stop blinking cursor (IGNORED) */
  926. break;
  927. case 20:
  928. term.mode &= ~MODE_CRLF;
  929. break;
  930. case 25:
  931. term.c.state |= CURSOR_HIDE;
  932. break;
  933. case 1049: /* = 1047 and 1048 */
  934. case 1047:
  935. if(IS_SET(MODE_ALTSCREEN)) {
  936. tclearregion(0, 0, term.col-1, term.row-1);
  937. tswapscreen();
  938. }
  939. if(escseq.arg[0] == 1047)
  940. break;
  941. case 1048:
  942. tcursor(CURSOR_LOAD);
  943. break;
  944. default:
  945. goto unknown;
  946. }
  947. } else {
  948. switch(escseq.arg[0]) {
  949. case 4:
  950. term.mode &= ~MODE_INSERT;
  951. break;
  952. default:
  953. goto unknown;
  954. }
  955. }
  956. break;
  957. case 'M': /* DL -- Delete <n> lines */
  958. DEFAULT(escseq.arg[0], 1);
  959. tdeleteline(escseq.arg[0]);
  960. break;
  961. case 'X': /* ECH -- Erase <n> char */
  962. DEFAULT(escseq.arg[0], 1);
  963. tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
  964. break;
  965. case 'P': /* DCH -- Delete <n> char */
  966. DEFAULT(escseq.arg[0], 1);
  967. tdeletechar(escseq.arg[0]);
  968. break;
  969. /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
  970. case 'd': /* VPA -- Move to <row> */
  971. DEFAULT(escseq.arg[0], 1);
  972. tmoveto(term.c.x, escseq.arg[0]-1);
  973. break;
  974. case 'h': /* SM -- Set terminal mode */
  975. if(escseq.priv) {
  976. switch(escseq.arg[0]) {
  977. case 1:
  978. term.mode |= MODE_APPKEYPAD;
  979. break;
  980. case 5: /* DECSCNM -- Reverve video */
  981. /* TODO: set REVERSE on the whole screen (f) */
  982. break;
  983. case 7:
  984. term.mode |= MODE_WRAP;
  985. break;
  986. case 20:
  987. term.mode |= MODE_CRLF;
  988. break;
  989. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  990. /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
  991. if(escseq.narg > 1 && escseq.arg[1] != 25)
  992. break;
  993. case 25:
  994. term.c.state &= ~CURSOR_HIDE;
  995. break;
  996. case 1049: /* = 1047 and 1048 */
  997. case 1047:
  998. if(IS_SET(MODE_ALTSCREEN))
  999. tclearregion(0, 0, term.col-1, term.row-1);
  1000. else
  1001. tswapscreen();
  1002. if(escseq.arg[0] == 1047)
  1003. break;
  1004. case 1048:
  1005. tcursor(CURSOR_SAVE);
  1006. break;
  1007. default: goto unknown;
  1008. }
  1009. } else {
  1010. switch(escseq.arg[0]) {
  1011. case 4:
  1012. term.mode |= MODE_INSERT;
  1013. break;
  1014. default: goto unknown;
  1015. }
  1016. };
  1017. break;
  1018. case 'm': /* SGR -- Terminal attribute (color) */
  1019. tsetattr(escseq.arg, escseq.narg);
  1020. break;
  1021. case 'r': /* DECSTBM -- Set Scrolling Region */
  1022. if(escseq.priv)
  1023. goto unknown;
  1024. else {
  1025. DEFAULT(escseq.arg[0], 1);
  1026. DEFAULT(escseq.arg[1], term.row);
  1027. tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
  1028. tmoveto(0, 0);
  1029. }
  1030. break;
  1031. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1032. tcursor(CURSOR_SAVE);
  1033. break;
  1034. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1035. tcursor(CURSOR_LOAD);
  1036. break;
  1037. }
  1038. }
  1039. void
  1040. csidump(void) {
  1041. int i;
  1042. printf("ESC [ %s", escseq.priv ? "? " : "");
  1043. if(escseq.narg)
  1044. for(i = 0; i < escseq.narg; i++)
  1045. printf("%d ", escseq.arg[i]);
  1046. if(escseq.mode)
  1047. putchar(escseq.mode);
  1048. putchar('\n');
  1049. }
  1050. void
  1051. csireset(void) {
  1052. memset(&escseq, 0, sizeof(escseq));
  1053. }
  1054. void
  1055. tputtab(void) {
  1056. int space = TAB - term.c.x % TAB;
  1057. tmoveto(term.c.x + space, term.c.y);
  1058. }
  1059. void
  1060. tputc(char *c) {
  1061. char ascii = *c;
  1062. if(term.esc & ESC_START) {
  1063. if(term.esc & ESC_CSI) {
  1064. escseq.buf[escseq.len++] = ascii;
  1065. if(BETWEEN(ascii, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
  1066. term.esc = 0;
  1067. csiparse(), csihandle();
  1068. }
  1069. /* TODO: handle other OSC */
  1070. } else if(term.esc & ESC_OSC) {
  1071. if(ascii == ';') {
  1072. term.titlelen = 0;
  1073. term.esc = ESC_START | ESC_TITLE;
  1074. }
  1075. } else if(term.esc & ESC_TITLE) {
  1076. if(ascii == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
  1077. term.esc = 0;
  1078. term.title[term.titlelen] = '\0';
  1079. XStoreName(xw.dis, xw.win, term.title);
  1080. } else {
  1081. term.title[term.titlelen++] = ascii;
  1082. }
  1083. } else if(term.esc & ESC_ALTCHARSET) {
  1084. switch(ascii) {
  1085. case '0': /* Line drawing crap */
  1086. term.c.attr.mode |= ATTR_GFX;
  1087. break;
  1088. case 'B': /* Back to regular text */
  1089. term.c.attr.mode &= ~ATTR_GFX;
  1090. break;
  1091. default:
  1092. printf("esc unhandled charset: ESC ( %c\n", ascii);
  1093. }
  1094. term.esc = 0;
  1095. } else {
  1096. switch(ascii) {
  1097. case '[':
  1098. term.esc |= ESC_CSI;
  1099. break;
  1100. case ']':
  1101. term.esc |= ESC_OSC;
  1102. break;
  1103. case '(':
  1104. term.esc |= ESC_ALTCHARSET;
  1105. break;
  1106. case 'D': /* IND -- Linefeed */
  1107. if(term.c.y == term.bot)
  1108. tscrollup(term.top, 1);
  1109. else
  1110. tmoveto(term.c.x, term.c.y+1);
  1111. term.esc = 0;
  1112. break;
  1113. case 'E': /* NEL -- Next line */
  1114. tnewline(1); /* always go to first col */
  1115. term.esc = 0;
  1116. break;
  1117. case 'M': /* RI -- Reverse index */
  1118. if(term.c.y == term.top)
  1119. tscrolldown(term.top, 1);
  1120. else
  1121. tmoveto(term.c.x, term.c.y-1);
  1122. term.esc = 0;
  1123. break;
  1124. case 'c': /* RIS -- Reset to inital state */
  1125. treset();
  1126. term.esc = 0;
  1127. break;
  1128. case '=': /* DECPAM -- Application keypad */
  1129. term.mode |= MODE_APPKEYPAD;
  1130. term.esc = 0;
  1131. break;
  1132. case '>': /* DECPNM -- Normal keypad */
  1133. term.mode &= ~MODE_APPKEYPAD;
  1134. term.esc = 0;
  1135. break;
  1136. case '7': /* DECSC -- Save Cursor */
  1137. tcursor(CURSOR_SAVE);
  1138. term.esc = 0;
  1139. break;
  1140. case '8': /* DECRC -- Restore Cursor */
  1141. tcursor(CURSOR_LOAD);
  1142. term.esc = 0;
  1143. break;
  1144. default:
  1145. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1146. (unsigned char) ascii, isprint(ascii)?ascii:'.');
  1147. term.esc = 0;
  1148. }
  1149. }
  1150. } else {
  1151. switch(ascii) {
  1152. case '\t':
  1153. tputtab();
  1154. break;
  1155. case '\b':
  1156. tmoveto(term.c.x-1, term.c.y);
  1157. break;
  1158. case '\r':
  1159. tmoveto(0, term.c.y);
  1160. break;
  1161. case '\f':
  1162. case '\v':
  1163. case '\n':
  1164. /* go to first col if the mode is set */
  1165. tnewline(IS_SET(MODE_CRLF));
  1166. break;
  1167. case '\a':
  1168. if(!(xw.state & WIN_FOCUSED))
  1169. xseturgency(1);
  1170. break;
  1171. case '\033':
  1172. csireset();
  1173. term.esc = ESC_START;
  1174. break;
  1175. default:
  1176. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1177. tnewline(1); /* always go to first col */
  1178. tsetchar(c);
  1179. if(term.c.x+1 < term.col)
  1180. tmoveto(term.c.x+1, term.c.y);
  1181. else
  1182. term.c.state |= CURSOR_WRAPNEXT;
  1183. break;
  1184. }
  1185. }
  1186. }
  1187. int
  1188. tresize(int col, int row) {
  1189. int i, x;
  1190. int minrow = MIN(row, term.row);
  1191. int mincol = MIN(col, term.col);
  1192. int slide = term.c.y - row + 1;
  1193. if(col < 1 || row < 1)
  1194. return 0;
  1195. /* free unneeded rows */
  1196. i = 0;
  1197. if(slide > 0) {
  1198. /* slide screen to keep cursor where we expect it -
  1199. * tscrollup would work here, but we can optimize to
  1200. * memmove because we're freeing the earlier lines */
  1201. for(/* i = 0 */; i < slide; i++) {
  1202. free(term.line[i]);
  1203. free(term.alt[i]);
  1204. }
  1205. memmove(term.line, term.line + slide, row * sizeof(Line));
  1206. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1207. }
  1208. for(i += row; i < term.row; i++) {
  1209. free(term.line[i]);
  1210. free(term.alt[i]);
  1211. }
  1212. /* resize to new height */
  1213. term.line = realloc(term.line, row * sizeof(Line));
  1214. term.alt = realloc(term.alt, row * sizeof(Line));
  1215. /* resize each row to new width, zero-pad if needed */
  1216. for(i = 0; i < minrow; i++) {
  1217. term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
  1218. term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
  1219. for(x = mincol; x < col; x++) {
  1220. term.line[i][x].state = 0;
  1221. term.alt[i][x].state = 0;
  1222. }
  1223. }
  1224. /* allocate any new rows */
  1225. for(/* i == minrow */; i < row; i++) {
  1226. term.line[i] = calloc(col, sizeof(Glyph));
  1227. term.alt [i] = calloc(col, sizeof(Glyph));
  1228. }
  1229. /* update terminal size */
  1230. term.col = col, term.row = row;
  1231. /* make use of the LIMIT in tmoveto */
  1232. tmoveto(term.c.x, term.c.y);
  1233. /* reset scrolling region */
  1234. tsetscroll(0, row-1);
  1235. return (slide > 0);
  1236. }
  1237. void
  1238. xresize(int col, int row) {
  1239. Pixmap newbuf;
  1240. int oldw, oldh;
  1241. oldw = xw.bufw;
  1242. oldh = xw.bufh;
  1243. xw.bufw = MAX(1, col * xw.cw);
  1244. xw.bufh = MAX(1, row * xw.ch);
  1245. newbuf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
  1246. XCopyArea(xw.dis, xw.buf, newbuf, dc.gc, 0, 0, xw.bufw, xw.bufh, 0, 0);
  1247. XFreePixmap(xw.dis, xw.buf);
  1248. XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
  1249. if(xw.bufw > oldw)
  1250. XFillRectangle(xw.dis, newbuf, dc.gc, oldw, 0,
  1251. xw.bufw-oldw, MIN(xw.bufh, oldh));
  1252. else if(xw.bufw < oldw && (BORDER > 0 || xw.w > xw.bufw))
  1253. XClearArea(xw.dis, xw.win, BORDER+xw.bufw, BORDER,
  1254. xw.w-xw.bufh-BORDER, BORDER+MIN(xw.bufh, oldh),
  1255. False);
  1256. if(xw.bufh > oldh)
  1257. XFillRectangle(xw.dis, newbuf, dc.gc, 0, oldh,
  1258. xw.bufw, xw.bufh-oldh);
  1259. else if(xw.bufh < oldh && (BORDER > 0 || xw.h > xw.bufh))
  1260. XClearArea(xw.dis, xw.win, BORDER, BORDER+xw.bufh,
  1261. xw.w-2*BORDER, xw.h-xw.bufh-BORDER,
  1262. False);
  1263. xw.buf = newbuf;
  1264. }
  1265. void
  1266. xloadcols(void) {
  1267. int i, r, g, b;
  1268. XColor color;
  1269. unsigned long white = WhitePixel(xw.dis, xw.scr);
  1270. for(i = 0; i < 16; i++) {
  1271. if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
  1272. dc.col[i] = white;
  1273. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1274. } else
  1275. dc.col[i] = color.pixel;
  1276. }
  1277. /* same colors as xterm */
  1278. for(r = 0; r < 6; r++)
  1279. for(g = 0; g < 6; g++)
  1280. for(b = 0; b < 6; b++) {
  1281. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1282. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1283. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1284. if (!XAllocColor(xw.dis, xw.cmap, &color)) {
  1285. dc.col[i] = white;
  1286. fprintf(stderr, "Could not allocate color %d\n", i);
  1287. } else
  1288. dc.col[i] = color.pixel;
  1289. i++;
  1290. }
  1291. for(r = 0; r < 24; r++, i++) {
  1292. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1293. if (!XAllocColor(xw.dis, xw.cmap, &color)) {
  1294. dc.col[i] = white;
  1295. fprintf(stderr, "Could not allocate color %d\n", i);
  1296. } else
  1297. dc.col[i] = color.pixel;
  1298. }
  1299. }
  1300. void
  1301. xclear(int x1, int y1, int x2, int y2) {
  1302. XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
  1303. XFillRectangle(xw.dis, xw.buf, dc.gc,
  1304. x1 * xw.cw, y1 * xw.ch,
  1305. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1306. }
  1307. void
  1308. xhints(void)
  1309. {
  1310. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1311. XWMHints wm = {.flags = InputHint, .input = 1};
  1312. XSizeHints size = {
  1313. .flags = PSize | PResizeInc | PBaseSize,
  1314. .height = xw.h,
  1315. .width = xw.w,
  1316. .height_inc = xw.ch,
  1317. .width_inc = xw.cw,
  1318. .base_height = 2*BORDER,
  1319. .base_width = 2*BORDER,
  1320. };
  1321. XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
  1322. }
  1323. XFontSet
  1324. xinitfont(char *fontstr)
  1325. {
  1326. XFontSet set;
  1327. char *def, **missing;
  1328. int n;
  1329. missing = NULL;
  1330. set = XCreateFontSet(xw.dis, fontstr, &missing, &n, &def);
  1331. if(missing) {
  1332. while(n--)
  1333. fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
  1334. XFreeStringList(missing);
  1335. }
  1336. return set;
  1337. }
  1338. void
  1339. xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing)
  1340. {
  1341. XFontStruct **xfonts;
  1342. char **font_names;
  1343. int i, n;
  1344. *ascent = *descent = *lbearing = *rbearing = 0;
  1345. n = XFontsOfFontSet(set, &xfonts, &font_names);
  1346. for(i = 0; i < n; i++) {
  1347. *ascent = MAX(*ascent, (*xfonts)->ascent);
  1348. *descent = MAX(*descent, (*xfonts)->descent);
  1349. *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
  1350. *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
  1351. xfonts++;
  1352. }
  1353. }
  1354. void
  1355. initfonts(char *fontstr, char *bfontstr)
  1356. {
  1357. if((dc.font.set = xinitfont(fontstr)) == NULL ||
  1358. (dc.bfont.set = xinitfont(bfontstr)) == NULL)
  1359. die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
  1360. xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
  1361. &dc.font.lbearing, &dc.font.rbearing);
  1362. xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
  1363. &dc.bfont.lbearing, &dc.bfont.rbearing);
  1364. }
  1365. void
  1366. xinit(void) {
  1367. XSetWindowAttributes attrs;
  1368. if(!(xw.dis = XOpenDisplay(NULL)))
  1369. die("Can't open display\n");
  1370. xw.scr = XDefaultScreen(xw.dis);
  1371. /* font */
  1372. initfonts(FONT, BOLDFONT);
  1373. /* XXX: Assuming same size for bold font */
  1374. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1375. xw.ch = dc.font.ascent + dc.font.descent;
  1376. /* colors */
  1377. xw.cmap = XDefaultColormap(xw.dis, xw.scr);
  1378. xloadcols();
  1379. /* window - default size */
  1380. xw.bufh = 24 * xw.ch;
  1381. xw.bufw = 80 * xw.cw;
  1382. xw.h = xw.bufh + 2*BORDER;
  1383. xw.w = xw.bufw + 2*BORDER;
  1384. attrs.background_pixel = dc.col[DefaultBG];
  1385. attrs.border_pixel = dc.col[DefaultBG];
  1386. attrs.bit_gravity = NorthWestGravity;
  1387. attrs.event_mask = FocusChangeMask | KeyPressMask
  1388. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1389. | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
  1390. attrs.colormap = xw.cmap;
  1391. xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
  1392. xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
  1393. XDefaultVisual(xw.dis, xw.scr),
  1394. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1395. | CWColormap,
  1396. &attrs);
  1397. xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
  1398. /* input methods */
  1399. xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
  1400. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1401. | XIMStatusNothing, XNClientWindow, xw.win,
  1402. XNFocusWindow, xw.win, NULL);
  1403. /* gc */
  1404. dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
  1405. XMapWindow(xw.dis, xw.win);
  1406. xhints();
  1407. XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
  1408. XSync(xw.dis, 0);
  1409. }
  1410. void
  1411. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1412. unsigned long xfg, xbg;
  1413. int winx = x*xw.cw, winy = y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1414. int i;
  1415. if(base.mode & ATTR_REVERSE)
  1416. xfg = dc.col[base.bg], xbg = dc.col[base.fg];
  1417. else
  1418. xfg = dc.col[base.fg], xbg = dc.col[base.bg];
  1419. XSetBackground(xw.dis, dc.gc, xbg);
  1420. XSetForeground(xw.dis, dc.gc, xfg);
  1421. if(base.mode & ATTR_GFX)
  1422. for(i = 0; i < bytelen; i++) {
  1423. char c = gfx[(unsigned int)s[i] % 256];
  1424. if(c)
  1425. s[i] = c;
  1426. else if(s[i] > 0x5f)
  1427. s[i] -= 0x5f;
  1428. }
  1429. XmbDrawImageString(xw.dis, xw.buf, base.mode & ATTR_BOLD ? dc.bfont.set : dc.font.set,
  1430. dc.gc, winx, winy, s, bytelen);
  1431. if(base.mode & ATTR_UNDERLINE)
  1432. XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1433. }
  1434. void
  1435. xdrawcursor(void) {
  1436. static int oldx = 0;
  1437. static int oldy = 0;
  1438. int sl;
  1439. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1440. LIMIT(oldx, 0, term.col-1);
  1441. LIMIT(oldy, 0, term.row-1);
  1442. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1443. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1444. /* remove the old cursor */
  1445. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1446. sl = utf8size(term.line[oldy][oldx].c);
  1447. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1448. } else
  1449. xclear(oldx, oldy, oldx, oldy);
  1450. /* draw the new one */
  1451. if(!(term.c.state & CURSOR_HIDE) && (xw.state & WIN_FOCUSED)) {
  1452. sl = utf8size(g.c);
  1453. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1454. oldx = term.c.x, oldy = term.c.y;
  1455. }
  1456. }
  1457. #ifdef DEBUG
  1458. /* basic drawing routines */
  1459. void
  1460. xdrawc(int x, int y, Glyph g) {
  1461. int sl = utf8size(g.c);
  1462. XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
  1463. XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
  1464. XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
  1465. XmbDrawImageString(xw.dis, xw.buf, g.mode&ATTR_BOLD?dc.bfont.fs:dc.font.fs,
  1466. dc.gc, r.x, r.y+dc.font.ascent, g.c, sl);
  1467. }
  1468. void
  1469. draw(int dummy) {
  1470. int x, y;
  1471. xclear(0, 0, term.col-1, term.row-1);
  1472. for(y = 0; y < term.row; y++)
  1473. for(x = 0; x < term.col; x++)
  1474. if(term.line[y][x].state & GLYPH_SET)
  1475. xdrawc(x, y, term.line[y][x]);
  1476. xdrawcursor();
  1477. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1478. XFlush(xw.dis);
  1479. }
  1480. #else
  1481. /* optimized drawing routine */
  1482. void
  1483. draw(int redraw_all) {
  1484. int ic, ib, x, y, ox, sl;
  1485. Glyph base, new;
  1486. char buf[DRAW_BUF_SIZ];
  1487. if(!(xw.state & WIN_VISIBLE))
  1488. return;
  1489. xclear(0, 0, term.col-1, term.row-1);
  1490. for(y = 0; y < term.row; y++) {
  1491. base = term.line[y][0];
  1492. ic = ib = ox = 0;
  1493. for(x = 0; x < term.col; x++) {
  1494. new = term.line[y][x];
  1495. if(sel.bx!=-1 && *(new.c) && selected(x, y))
  1496. new.mode ^= ATTR_REVERSE;
  1497. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1498. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1499. xdraws(buf, base, ox, y, ic, ib);
  1500. ic = ib = 0;
  1501. }
  1502. if(new.state & GLYPH_SET) {
  1503. if(ib == 0) {
  1504. ox = x;
  1505. base = new;
  1506. }
  1507. sl = utf8size(new.c);
  1508. memcpy(buf+ib, new.c, sl);
  1509. ib += sl;
  1510. ++ic;
  1511. }
  1512. }
  1513. if(ib > 0)
  1514. xdraws(buf, base, ox, y, ic, ib);
  1515. }
  1516. xdrawcursor();
  1517. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1518. }
  1519. #endif
  1520. void
  1521. expose(XEvent *ev) {
  1522. XExposeEvent *e = &ev->xexpose;
  1523. if(xw.state & WIN_REDRAW) {
  1524. if(!e->count) {
  1525. xw.state &= ~WIN_REDRAW;
  1526. draw(SCREEN_REDRAW);
  1527. }
  1528. } else
  1529. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
  1530. e->width, e->height, e->x, e->y);
  1531. }
  1532. void
  1533. visibility(XEvent *ev) {
  1534. XVisibilityEvent *e = &ev->xvisibility;
  1535. if(e->state == VisibilityFullyObscured)
  1536. xw.state &= ~WIN_VISIBLE;
  1537. else if(!(xw.state & WIN_VISIBLE))
  1538. /* need a full redraw for next Expose, not just a buf copy */
  1539. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1540. }
  1541. void
  1542. unmap(XEvent *ev) {
  1543. xw.state &= ~WIN_VISIBLE;
  1544. }
  1545. void
  1546. xseturgency(int add) {
  1547. XWMHints *h = XGetWMHints(xw.dis, xw.win);
  1548. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1549. XSetWMHints(xw.dis, xw.win, h);
  1550. XFree(h);
  1551. }
  1552. void
  1553. focus(XEvent *ev) {
  1554. if(ev->type == FocusIn) {
  1555. xw.state |= WIN_FOCUSED;
  1556. xseturgency(0);
  1557. } else
  1558. xw.state &= ~WIN_FOCUSED;
  1559. draw(SCREEN_UPDATE);
  1560. }
  1561. char*
  1562. kmap(KeySym k) {
  1563. int i;
  1564. for(i = 0; i < LEN(key); i++)
  1565. if(key[i].k == k)
  1566. return (char*)key[i].s;
  1567. return NULL;
  1568. }
  1569. void
  1570. kpress(XEvent *ev) {
  1571. XKeyEvent *e = &ev->xkey;
  1572. KeySym ksym;
  1573. char buf[32];
  1574. char *customkey;
  1575. int len;
  1576. int meta;
  1577. int shift;
  1578. Status status;
  1579. meta = e->state & Mod1Mask;
  1580. shift = e->state & ShiftMask;
  1581. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1582. /* 1. custom keys from config.h */
  1583. if((customkey = kmap(ksym)))
  1584. ttywrite(customkey, strlen(customkey));
  1585. /* 2. hardcoded (overrides X lookup) */
  1586. else
  1587. switch(ksym) {
  1588. case XK_Up:
  1589. case XK_Down:
  1590. case XK_Left:
  1591. case XK_Right:
  1592. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
  1593. ttywrite(buf, 3);
  1594. break;
  1595. case XK_Insert:
  1596. if(shift)
  1597. selpaste();
  1598. break;
  1599. case XK_Return:
  1600. if(IS_SET(MODE_CRLF))
  1601. ttywrite("\r\n", 2);
  1602. else
  1603. ttywrite("\r", 1);
  1604. break;
  1605. /* 3. X lookup */
  1606. default:
  1607. if(len > 0) {
  1608. buf[sizeof(buf)-1] = '\0';
  1609. if(meta && len == 1)
  1610. ttywrite("\033", 1);
  1611. ttywrite(buf, len);
  1612. } else /* 4. nothing to send */
  1613. fprintf(stderr, "errkey: %d\n", (int)ksym);
  1614. break;
  1615. }
  1616. }
  1617. void
  1618. resize(XEvent *e) {
  1619. int col, row;
  1620. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  1621. return;
  1622. xw.w = e->xconfigure.width;
  1623. xw.h = e->xconfigure.height;
  1624. col = (xw.w - 2*BORDER) / xw.cw;
  1625. row = (xw.h - 2*BORDER) / xw.ch;
  1626. if(col == term.col && row == term.row)
  1627. return;
  1628. if(tresize(col, row))
  1629. draw(SCREEN_REDRAW);
  1630. ttyresize(col, row);
  1631. xresize(col, row);
  1632. }
  1633. void
  1634. run(void) {
  1635. XEvent ev;
  1636. fd_set rfd;
  1637. int xfd = XConnectionNumber(xw.dis);
  1638. for(;;) {
  1639. FD_ZERO(&rfd);
  1640. FD_SET(cmdfd, &rfd);
  1641. FD_SET(xfd, &rfd);
  1642. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
  1643. if(errno == EINTR)
  1644. continue;
  1645. die("select failed: %s\n", SERRNO);
  1646. }
  1647. if(FD_ISSET(cmdfd, &rfd)) {
  1648. ttyread();
  1649. draw(SCREEN_UPDATE);
  1650. }
  1651. while(XPending(xw.dis)) {
  1652. XNextEvent(xw.dis, &ev);
  1653. if (XFilterEvent(&ev, xw.win))
  1654. continue;
  1655. if(handler[ev.type])
  1656. (handler[ev.type])(&ev);
  1657. }
  1658. }
  1659. }
  1660. int
  1661. main(int argc, char *argv[]) {
  1662. int i;
  1663. for(i = 1; i < argc; i++) {
  1664. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  1665. case 't':
  1666. if(++i < argc) opt_title = argv[i];
  1667. break;
  1668. case 'c':
  1669. if(++i < argc) opt_class = argv[i];
  1670. break;
  1671. case 'e':
  1672. if(++i < argc) opt_cmd = argv[i];
  1673. break;
  1674. case 'v':
  1675. default:
  1676. die(USAGE);
  1677. }
  1678. }
  1679. setlocale(LC_CTYPE, "");
  1680. tnew(80, 24);
  1681. ttynew();
  1682. xinit();
  1683. selinit();
  1684. run();
  1685. return 0;
  1686. }