My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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