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.

1884 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
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
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/Xatom.h>
  20. #include <X11/Xlib.h>
  21. #include <X11/Xutil.h>
  22. #include <X11/cursorfont.h>
  23. #include <X11/keysym.h>
  24. #if defined(__linux)
  25. #include <pty.h>
  26. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  27. #include <util.h>
  28. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  29. #include <libutil.h>
  30. #endif
  31. #define USAGE \
  32. "st-" VERSION ", (c) 2010 st engineers\n" \
  33. "usage: st [-t title] [-c class] [-v] [-e cmd]\n"
  34. /* Arbitrary sizes */
  35. #define ESC_TITLE_SIZ 256
  36. #define ESC_BUF_SIZ 256
  37. #define ESC_ARG_SIZ 16
  38. #define DRAW_BUF_SIZ 1024
  39. #define UTF_SIZ 4
  40. #define SERRNO strerror(errno)
  41. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  42. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  43. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  44. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  45. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  46. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  47. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  48. #define IS_SET(flag) (term.mode & (flag))
  49. /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
  50. enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
  51. enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT,
  52. CURSOR_SAVE, CURSOR_LOAD };
  53. enum { CURSOR_DEFAULT = 0, CURSOR_HIDE = 1, CURSOR_WRAPNEXT = 2 };
  54. enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
  55. enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4, MODE_ALTSCREEN=8,
  56. MODE_CRLF=16 };
  57. enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
  58. enum { SCREEN_UPDATE, SCREEN_REDRAW };
  59. enum { WIN_VISIBLE=1, WIN_REDRAW=2, WIN_FOCUSED=4 };
  60. #undef B0
  61. enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
  62. typedef struct {
  63. char c[UTF_SIZ]; /* character code */
  64. char mode; /* attribute flags */
  65. int fg; /* foreground */
  66. int bg; /* background */
  67. char state; /* state flags */
  68. } Glyph;
  69. typedef Glyph* Line;
  70. typedef struct {
  71. Glyph attr; /* current char attributes */
  72. int x;
  73. int y;
  74. char state;
  75. } TCursor;
  76. /* CSI Escape sequence structs */
  77. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  78. typedef struct {
  79. char buf[ESC_BUF_SIZ]; /* raw string */
  80. int len; /* raw string length */
  81. char priv;
  82. int arg[ESC_ARG_SIZ];
  83. int narg; /* nb of args */
  84. char mode;
  85. } CSIEscape;
  86. /* Internal representation of the screen */
  87. typedef struct {
  88. int row; /* nb row */
  89. int col; /* nb col */
  90. Line* line; /* screen */
  91. Line* alt; /* alternate screen */
  92. TCursor c; /* cursor */
  93. int top; /* top scroll limit */
  94. int bot; /* bottom scroll limit */
  95. int mode; /* terminal mode flags */
  96. int esc; /* escape state flags */
  97. char title[ESC_TITLE_SIZ];
  98. int titlelen;
  99. } Term;
  100. /* Purely graphic info */
  101. typedef struct {
  102. Display* dpy;
  103. Colormap cmap;
  104. Window win;
  105. Pixmap buf;
  106. XIM xim;
  107. XIC xic;
  108. int scr;
  109. int w; /* window width */
  110. int h; /* window height */
  111. int bufw; /* pixmap width */
  112. int bufh; /* pixmap height */
  113. int ch; /* char height */
  114. int cw; /* char width */
  115. char state; /* focus, redraw, visible */
  116. } XWindow;
  117. typedef struct {
  118. KeySym k;
  119. char s[ESC_BUF_SIZ];
  120. } Key;
  121. /* Drawing Context */
  122. typedef struct {
  123. unsigned long col[256];
  124. GC gc;
  125. struct {
  126. int ascent;
  127. int descent;
  128. short lbearing;
  129. short rbearing;
  130. XFontSet set;
  131. } font, bfont;
  132. } DC;
  133. /* TODO: use better name for vars... */
  134. typedef struct {
  135. int mode;
  136. int bx, by;
  137. int ex, ey;
  138. struct {int x, y;} b, e;
  139. char *clip;
  140. Atom xtarget;
  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 utf8decode(char *, long *);
  201. static int utf8encode(long *, char *);
  202. static int utf8size(char *);
  203. static int isfullutf8(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. int
  230. utf8decode(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. int
  267. utf8encode(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. int
  301. isfullutf8(char *s, int b) {
  302. unsigned char *c1, *c2, *c3;
  303. c1 = (unsigned char *) s;
  304. c2 = (unsigned char *) ++s;
  305. c3 = (unsigned char *) ++s;
  306. if(b < 1)
  307. return 0;
  308. else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
  309. return 0;
  310. else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
  311. ((b == 1) ||
  312. ((b == 2) && (*c2&(B7|B6)) == B7)))
  313. return 0;
  314. else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
  315. ((b == 1) ||
  316. ((b == 2) && (*c2&(B7|B6)) == B7) ||
  317. ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
  318. return 0;
  319. else
  320. return 1;
  321. }
  322. int
  323. utf8size(char *s) {
  324. unsigned char c = *s;
  325. if (~c&B7)
  326. return 1;
  327. else if ((c&(B7|B6|B5)) == (B7|B6))
  328. return 2;
  329. else if ((c&(B7|B6|B5|B4)) == (B7|B6|B5))
  330. return 3;
  331. else
  332. return 4;
  333. }
  334. void
  335. selinit(void) {
  336. sel.mode = 0;
  337. sel.bx = -1;
  338. sel.clip = NULL;
  339. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  340. if(sel.xtarget == None)
  341. sel.xtarget = XA_STRING;
  342. }
  343. static inline int
  344. selected(int x, int y) {
  345. if(sel.ey == y && sel.by == y) {
  346. int bx = MIN(sel.bx, sel.ex);
  347. int ex = MAX(sel.bx, sel.ex);
  348. return BETWEEN(x, bx, ex);
  349. }
  350. return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
  351. || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
  352. }
  353. void
  354. getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
  355. if(b)
  356. *b = e->xbutton.button;
  357. *x = (e->xbutton.x - BORDER)/xw.cw;
  358. *y = (e->xbutton.y - BORDER)/xw.ch;
  359. sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
  360. sel.b.y = MIN(sel.by, sel.ey);
  361. sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
  362. sel.e.y = MAX(sel.by, sel.ey);
  363. }
  364. void
  365. bpress(XEvent *e) {
  366. sel.mode = 1;
  367. sel.ex = sel.bx = (e->xbutton.x - BORDER)/xw.cw;
  368. sel.ey = sel.by = (e->xbutton.y - BORDER)/xw.ch;
  369. }
  370. void
  371. selcopy(void) {
  372. char *str, *ptr;
  373. int x, y, sz, sl, ls = 0;
  374. if(sel.bx == -1)
  375. str = NULL;
  376. else {
  377. sz = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
  378. ptr = str = malloc(sz);
  379. for(y = 0; y < term.row; y++) {
  380. for(x = 0; x < term.col; x++)
  381. if(term.line[y][x].state & GLYPH_SET && (ls = selected(x, y))) {
  382. sl = utf8size(term.line[y][x].c);
  383. memcpy(ptr, term.line[y][x].c, sl);
  384. ptr += sl;
  385. }
  386. if(ls && y < sel.e.y)
  387. *ptr++ = '\n';
  388. }
  389. *ptr = 0;
  390. }
  391. xsetsel(str);
  392. }
  393. void
  394. selnotify(XEvent *e) {
  395. unsigned long nitems;
  396. unsigned long ofs, rem;
  397. int format;
  398. unsigned char *data;
  399. Atom type;
  400. ofs = 0;
  401. do {
  402. if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
  403. False, AnyPropertyType, &type, &format,
  404. &nitems, &rem, &data)) {
  405. fprintf(stderr, "Clipboard allocation failed\n");
  406. return;
  407. }
  408. ttywrite((const char *) data, nitems * format / 8);
  409. XFree(data);
  410. /* number of 32-bit chunks returned */
  411. ofs += nitems * format / 32;
  412. } while(rem > 0);
  413. }
  414. void
  415. selpaste() {
  416. XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
  417. }
  418. void
  419. selrequest(XEvent *e) {
  420. XSelectionRequestEvent *xsre;
  421. XSelectionEvent xev;
  422. Atom xa_targets;
  423. xsre = (XSelectionRequestEvent *) e;
  424. xev.type = SelectionNotify;
  425. xev.requestor = xsre->requestor;
  426. xev.selection = xsre->selection;
  427. xev.target = xsre->target;
  428. xev.time = xsre->time;
  429. /* reject */
  430. xev.property = None;
  431. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  432. if(xsre->target == xa_targets) {
  433. /* respond with the supported type */
  434. Atom string = sel.xtarget;
  435. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  436. XA_ATOM, 32, PropModeReplace,
  437. (unsigned char *) &string, 1);
  438. xev.property = xsre->property;
  439. } else if(xsre->target == sel.xtarget) {
  440. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  441. xsre->target, 8, PropModeReplace,
  442. (unsigned char *) sel.clip, strlen(sel.clip));
  443. xev.property = xsre->property;
  444. }
  445. /* all done, send a notification to the listener */
  446. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  447. fprintf(stderr, "Error sending SelectionNotify event\n");
  448. }
  449. void
  450. xsetsel(char *str) {
  451. /* register the selection for both the clipboard and the primary */
  452. Atom clipboard;
  453. free(sel.clip);
  454. sel.clip = str;
  455. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
  456. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  457. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  458. XFlush(xw.dpy);
  459. }
  460. /* TODO: doubleclick to select word */
  461. void
  462. brelease(XEvent *e) {
  463. int b;
  464. sel.mode = 0;
  465. getbuttoninfo(e, &b, &sel.ex, &sel.ey);
  466. if(sel.bx==sel.ex && sel.by==sel.ey) {
  467. sel.bx = -1;
  468. if(b==2)
  469. selpaste();
  470. } else {
  471. if(b==1)
  472. selcopy();
  473. }
  474. draw(1);
  475. }
  476. void
  477. bmotion(XEvent *e) {
  478. if (sel.mode) {
  479. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  480. /* XXX: draw() can't keep up, disabled for now.
  481. selection is visible on button release.
  482. draw(1); */
  483. }
  484. }
  485. void
  486. die(const char *errstr, ...) {
  487. va_list ap;
  488. va_start(ap, errstr);
  489. vfprintf(stderr, errstr, ap);
  490. va_end(ap);
  491. exit(EXIT_FAILURE);
  492. }
  493. void
  494. execsh(void) {
  495. char **args;
  496. char *envshell = getenv("SHELL");
  497. DEFAULT(envshell, "sh");
  498. putenv("TERM="TNAME);
  499. args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
  500. execvp(args[0], args);
  501. exit(EXIT_FAILURE);
  502. }
  503. void
  504. sigchld(int a) {
  505. int stat = 0;
  506. if(waitpid(pid, &stat, 0) < 0)
  507. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  508. if(WIFEXITED(stat))
  509. exit(WEXITSTATUS(stat));
  510. else
  511. exit(EXIT_FAILURE);
  512. }
  513. void
  514. ttynew(void) {
  515. int m, s;
  516. /* seems to work fine on linux, openbsd and freebsd */
  517. struct winsize w = {term.row, term.col, 0, 0};
  518. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  519. die("openpty failed: %s\n", SERRNO);
  520. switch(pid = fork()) {
  521. case -1:
  522. die("fork failed\n");
  523. break;
  524. case 0:
  525. setsid(); /* create a new process group */
  526. dup2(s, STDIN_FILENO);
  527. dup2(s, STDOUT_FILENO);
  528. dup2(s, STDERR_FILENO);
  529. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  530. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  531. close(s);
  532. close(m);
  533. execsh();
  534. break;
  535. default:
  536. close(s);
  537. cmdfd = m;
  538. signal(SIGCHLD, sigchld);
  539. }
  540. }
  541. void
  542. dump(char c) {
  543. static int col;
  544. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  545. if(++col % 10 == 0)
  546. fprintf(stderr, "\n");
  547. }
  548. void
  549. ttyread(void) {
  550. static char buf[BUFSIZ];
  551. static int buflen = 0;
  552. char *ptr;
  553. char s[UTF_SIZ];
  554. int charsize; /* size of utf8 char in bytes */
  555. long utf8c;
  556. int ret;
  557. /* append read bytes to unprocessed bytes */
  558. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  559. die("Couldn't read from shell: %s\n", SERRNO);
  560. /* process every complete utf8 char */
  561. buflen += ret;
  562. ptr = buf;
  563. while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
  564. charsize = utf8decode(ptr, &utf8c);
  565. utf8encode(&utf8c, s);
  566. tputc(s);
  567. ptr += charsize;
  568. buflen -= charsize;
  569. }
  570. /* keep any uncomplete utf8 char for the next call */
  571. memmove(buf, ptr, buflen);
  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. fprintf(stderr, "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.dpy, 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. fprintf(stderr, "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.dpy, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dpy, xw.scr));
  1256. XCopyArea(xw.dpy, xw.buf, newbuf, dc.gc, 0, 0, xw.bufw, xw.bufh, 0, 0);
  1257. XFreePixmap(xw.dpy, xw.buf);
  1258. XSetForeground(xw.dpy, dc.gc, dc.col[DefaultBG]);
  1259. if(xw.bufw > oldw)
  1260. XFillRectangle(xw.dpy, 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.dpy, 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.dpy, 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.dpy, 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.dpy, xw.scr);
  1280. for(i = 0; i < 16; i++) {
  1281. if (!XAllocNamedColor(xw.dpy, 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.dpy, 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.dpy, 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.dpy, dc.gc, dc.col[DefaultBG]);
  1313. XFillRectangle(xw.dpy, 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.dpy, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
  1332. }
  1333. XFontSet
  1334. xinitfont(char *fontstr)
  1335. {
  1336. XFontSet set;
  1337. char *def, **missing;
  1338. int n;
  1339. missing = NULL;
  1340. set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
  1341. if(missing) {
  1342. while(n--)
  1343. fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
  1344. XFreeStringList(missing);
  1345. }
  1346. return set;
  1347. }
  1348. void
  1349. xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing)
  1350. {
  1351. XFontStruct **xfonts;
  1352. char **font_names;
  1353. int i, n;
  1354. *ascent = *descent = *lbearing = *rbearing = 0;
  1355. n = XFontsOfFontSet(set, &xfonts, &font_names);
  1356. for(i = 0; i < n; i++) {
  1357. *ascent = MAX(*ascent, (*xfonts)->ascent);
  1358. *descent = MAX(*descent, (*xfonts)->descent);
  1359. *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
  1360. *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
  1361. xfonts++;
  1362. }
  1363. }
  1364. void
  1365. initfonts(char *fontstr, char *bfontstr)
  1366. {
  1367. if((dc.font.set = xinitfont(fontstr)) == NULL ||
  1368. (dc.bfont.set = xinitfont(bfontstr)) == NULL)
  1369. die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
  1370. xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
  1371. &dc.font.lbearing, &dc.font.rbearing);
  1372. xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
  1373. &dc.bfont.lbearing, &dc.bfont.rbearing);
  1374. }
  1375. void
  1376. xinit(void) {
  1377. XSetWindowAttributes attrs;
  1378. Cursor cursor;
  1379. if(!(xw.dpy = XOpenDisplay(NULL)))
  1380. die("Can't open display\n");
  1381. xw.scr = XDefaultScreen(xw.dpy);
  1382. /* font */
  1383. initfonts(FONT, BOLDFONT);
  1384. /* XXX: Assuming same size for bold font */
  1385. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1386. xw.ch = dc.font.ascent + dc.font.descent;
  1387. /* colors */
  1388. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1389. xloadcols();
  1390. /* window - default size */
  1391. xw.bufh = 24 * xw.ch;
  1392. xw.bufw = 80 * xw.cw;
  1393. xw.h = xw.bufh + 2*BORDER;
  1394. xw.w = xw.bufw + 2*BORDER;
  1395. attrs.background_pixel = dc.col[DefaultBG];
  1396. attrs.border_pixel = dc.col[DefaultBG];
  1397. attrs.bit_gravity = NorthWestGravity;
  1398. attrs.event_mask = FocusChangeMask | KeyPressMask
  1399. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1400. | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
  1401. attrs.colormap = xw.cmap;
  1402. xw.win = XCreateWindow(xw.dpy, XRootWindow(xw.dpy, xw.scr), 0, 0,
  1403. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1404. XDefaultVisual(xw.dpy, xw.scr),
  1405. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1406. | CWColormap,
  1407. &attrs);
  1408. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dpy, xw.scr));
  1409. /* input methods */
  1410. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1411. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1412. | XIMStatusNothing, XNClientWindow, xw.win,
  1413. XNFocusWindow, xw.win, NULL);
  1414. /* gc */
  1415. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1416. /* white cursor, black outline */
  1417. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1418. XDefineCursor(xw.dpy, xw.win, cursor);
  1419. XRecolorCursor(xw.dpy, cursor,
  1420. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1421. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1422. XMapWindow(xw.dpy, xw.win);
  1423. xhints();
  1424. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1425. XSync(xw.dpy, 0);
  1426. }
  1427. void
  1428. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1429. unsigned long xfg, xbg;
  1430. int winx = x*xw.cw, winy = y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1431. int i;
  1432. if(base.mode & ATTR_REVERSE)
  1433. xfg = dc.col[base.bg], xbg = dc.col[base.fg];
  1434. else
  1435. xfg = dc.col[base.fg], xbg = dc.col[base.bg];
  1436. XSetBackground(xw.dpy, dc.gc, xbg);
  1437. XSetForeground(xw.dpy, dc.gc, xfg);
  1438. if(base.mode & ATTR_GFX) {
  1439. for(i = 0; i < bytelen; i++) {
  1440. char c = gfx[(unsigned int)s[i] % 256];
  1441. if(c)
  1442. s[i] = c;
  1443. else if(s[i] > 0x5f)
  1444. s[i] -= 0x5f;
  1445. }
  1446. }
  1447. XmbDrawImageString(xw.dpy, xw.buf, base.mode & ATTR_BOLD ? dc.bfont.set : dc.font.set,
  1448. dc.gc, winx, winy, s, bytelen);
  1449. if(base.mode & ATTR_UNDERLINE)
  1450. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1451. }
  1452. void
  1453. xdrawcursor(void) {
  1454. static int oldx = 0;
  1455. static int oldy = 0;
  1456. int sl;
  1457. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1458. LIMIT(oldx, 0, term.col-1);
  1459. LIMIT(oldy, 0, term.row-1);
  1460. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1461. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1462. /* remove the old cursor */
  1463. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1464. sl = utf8size(term.line[oldy][oldx].c);
  1465. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1466. } else
  1467. xclear(oldx, oldy, oldx, oldy);
  1468. /* draw the new one */
  1469. if(!(term.c.state & CURSOR_HIDE) && (xw.state & WIN_FOCUSED)) {
  1470. sl = utf8size(g.c);
  1471. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1472. oldx = term.c.x, oldy = term.c.y;
  1473. }
  1474. }
  1475. #ifdef DEBUG
  1476. /* basic drawing routines */
  1477. void
  1478. xdrawc(int x, int y, Glyph g) {
  1479. int sl = utf8size(g.c);
  1480. XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
  1481. XSetBackground(xw.dpy, dc.gc, dc.col[g.bg]);
  1482. XSetForeground(xw.dpy, dc.gc, dc.col[g.fg]);
  1483. XmbDrawImageString(xw.dpy, xw.buf, g.mode&ATTR_BOLD?dc.bfont.fs:dc.font.fs,
  1484. dc.gc, r.x, r.y+dc.font.ascent, g.c, sl);
  1485. }
  1486. void
  1487. draw(int dummy) {
  1488. int x, y;
  1489. xclear(0, 0, term.col-1, term.row-1);
  1490. for(y = 0; y < term.row; y++)
  1491. for(x = 0; x < term.col; x++)
  1492. if(term.line[y][x].state & GLYPH_SET)
  1493. xdrawc(x, y, term.line[y][x]);
  1494. xdrawcursor();
  1495. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1496. XFlush(xw.dpy);
  1497. }
  1498. #else
  1499. /* optimized drawing routine */
  1500. void
  1501. draw(int redraw_all) {
  1502. int ic, ib, x, y, ox, sl;
  1503. Glyph base, new;
  1504. char buf[DRAW_BUF_SIZ];
  1505. if(!(xw.state & WIN_VISIBLE))
  1506. return;
  1507. xclear(0, 0, term.col-1, term.row-1);
  1508. for(y = 0; y < term.row; y++) {
  1509. base = term.line[y][0];
  1510. ic = ib = ox = 0;
  1511. for(x = 0; x < term.col; x++) {
  1512. new = term.line[y][x];
  1513. if(sel.bx!=-1 && *(new.c) && selected(x, y))
  1514. new.mode ^= ATTR_REVERSE;
  1515. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1516. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1517. xdraws(buf, base, ox, y, ic, ib);
  1518. ic = ib = 0;
  1519. }
  1520. if(new.state & GLYPH_SET) {
  1521. if(ib == 0) {
  1522. ox = x;
  1523. base = new;
  1524. }
  1525. sl = utf8size(new.c);
  1526. memcpy(buf+ib, new.c, sl);
  1527. ib += sl;
  1528. ++ic;
  1529. }
  1530. }
  1531. if(ib > 0)
  1532. xdraws(buf, base, ox, y, ic, ib);
  1533. }
  1534. xdrawcursor();
  1535. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1536. }
  1537. #endif
  1538. void
  1539. expose(XEvent *ev) {
  1540. XExposeEvent *e = &ev->xexpose;
  1541. if(xw.state & WIN_REDRAW) {
  1542. if(!e->count) {
  1543. xw.state &= ~WIN_REDRAW;
  1544. draw(SCREEN_REDRAW);
  1545. }
  1546. } else
  1547. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
  1548. e->width, e->height, e->x, e->y);
  1549. }
  1550. void
  1551. visibility(XEvent *ev) {
  1552. XVisibilityEvent *e = &ev->xvisibility;
  1553. if(e->state == VisibilityFullyObscured)
  1554. xw.state &= ~WIN_VISIBLE;
  1555. else if(!(xw.state & WIN_VISIBLE))
  1556. /* need a full redraw for next Expose, not just a buf copy */
  1557. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1558. }
  1559. void
  1560. unmap(XEvent *ev) {
  1561. xw.state &= ~WIN_VISIBLE;
  1562. }
  1563. void
  1564. xseturgency(int add) {
  1565. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1566. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1567. XSetWMHints(xw.dpy, xw.win, h);
  1568. XFree(h);
  1569. }
  1570. void
  1571. focus(XEvent *ev) {
  1572. if(ev->type == FocusIn) {
  1573. xw.state |= WIN_FOCUSED;
  1574. xseturgency(0);
  1575. } else
  1576. xw.state &= ~WIN_FOCUSED;
  1577. draw(SCREEN_UPDATE);
  1578. }
  1579. char*
  1580. kmap(KeySym k) {
  1581. int i;
  1582. for(i = 0; i < LEN(key); i++)
  1583. if(key[i].k == k)
  1584. return (char*)key[i].s;
  1585. return NULL;
  1586. }
  1587. void
  1588. kpress(XEvent *ev) {
  1589. XKeyEvent *e = &ev->xkey;
  1590. KeySym ksym;
  1591. char buf[32];
  1592. char *customkey;
  1593. int len;
  1594. int meta;
  1595. int shift;
  1596. Status status;
  1597. meta = e->state & Mod1Mask;
  1598. shift = e->state & ShiftMask;
  1599. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1600. /* 1. custom keys from config.h */
  1601. if((customkey = kmap(ksym)))
  1602. ttywrite(customkey, strlen(customkey));
  1603. /* 2. hardcoded (overrides X lookup) */
  1604. else
  1605. switch(ksym) {
  1606. case XK_Up:
  1607. case XK_Down:
  1608. case XK_Left:
  1609. case XK_Right:
  1610. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
  1611. ttywrite(buf, 3);
  1612. break;
  1613. case XK_Insert:
  1614. if(shift)
  1615. selpaste();
  1616. break;
  1617. case XK_Return:
  1618. if(IS_SET(MODE_CRLF))
  1619. ttywrite("\r\n", 2);
  1620. else
  1621. ttywrite("\r", 1);
  1622. break;
  1623. /* 3. X lookup */
  1624. default:
  1625. if(len > 0) {
  1626. if(meta && len == 1)
  1627. ttywrite("\033", 1);
  1628. ttywrite(buf, len);
  1629. }
  1630. break;
  1631. }
  1632. }
  1633. void
  1634. resize(XEvent *e) {
  1635. int col, row;
  1636. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  1637. return;
  1638. xw.w = e->xconfigure.width;
  1639. xw.h = e->xconfigure.height;
  1640. col = (xw.w - 2*BORDER) / xw.cw;
  1641. row = (xw.h - 2*BORDER) / xw.ch;
  1642. if(col == term.col && row == term.row)
  1643. return;
  1644. if(tresize(col, row))
  1645. draw(SCREEN_REDRAW);
  1646. ttyresize(col, row);
  1647. xresize(col, row);
  1648. }
  1649. void
  1650. run(void) {
  1651. XEvent ev;
  1652. fd_set rfd;
  1653. int xfd = XConnectionNumber(xw.dpy);
  1654. for(;;) {
  1655. FD_ZERO(&rfd);
  1656. FD_SET(cmdfd, &rfd);
  1657. FD_SET(xfd, &rfd);
  1658. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
  1659. if(errno == EINTR)
  1660. continue;
  1661. die("select failed: %s\n", SERRNO);
  1662. }
  1663. if(FD_ISSET(cmdfd, &rfd)) {
  1664. ttyread();
  1665. draw(SCREEN_UPDATE);
  1666. }
  1667. while(XPending(xw.dpy)) {
  1668. XNextEvent(xw.dpy, &ev);
  1669. if (XFilterEvent(&ev, xw.win))
  1670. continue;
  1671. if(handler[ev.type])
  1672. (handler[ev.type])(&ev);
  1673. }
  1674. }
  1675. }
  1676. int
  1677. main(int argc, char *argv[]) {
  1678. int i;
  1679. for(i = 1; i < argc; i++) {
  1680. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  1681. case 't':
  1682. if(++i < argc) opt_title = argv[i];
  1683. break;
  1684. case 'c':
  1685. if(++i < argc) opt_class = argv[i];
  1686. break;
  1687. case 'e':
  1688. if(++i < argc) opt_cmd = &argv[i];
  1689. break;
  1690. case 'v':
  1691. default:
  1692. die(USAGE);
  1693. }
  1694. /* -e eats every remaining arguments */
  1695. if(opt_cmd)
  1696. break;
  1697. }
  1698. setlocale(LC_CTYPE, "");
  1699. tnew(80, 24);
  1700. ttynew();
  1701. xinit();
  1702. selinit();
  1703. run();
  1704. return 0;
  1705. }