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.

2162 lines
48 KiB

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