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.

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