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.

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