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.

2158 lines
48 KiB

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