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.

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