Simple Terminal from SuckLess
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.

1860 lines
42 KiB

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