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.

2192 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
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 'J': /* ED -- Clear screen */
  1090. sel.bx = -1;
  1091. switch(escseq.arg[0]) {
  1092. case 0: /* below */
  1093. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1094. if(term.c.y < term.row-1)
  1095. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  1096. break;
  1097. case 1: /* above */
  1098. if(term.c.y > 1)
  1099. tclearregion(0, 0, term.col-1, term.c.y-1);
  1100. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1101. break;
  1102. case 2: /* all */
  1103. tclearregion(0, 0, term.col-1, term.row-1);
  1104. break;
  1105. default:
  1106. goto unknown;
  1107. }
  1108. break;
  1109. case 'K': /* EL -- Clear line */
  1110. switch(escseq.arg[0]) {
  1111. case 0: /* right */
  1112. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1113. break;
  1114. case 1: /* left */
  1115. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1116. break;
  1117. case 2: /* all */
  1118. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1119. break;
  1120. }
  1121. break;
  1122. case 'S': /* SU -- Scroll <n> line up */
  1123. DEFAULT(escseq.arg[0], 1);
  1124. tscrollup(term.top, escseq.arg[0]);
  1125. break;
  1126. case 'T': /* SD -- Scroll <n> line down */
  1127. DEFAULT(escseq.arg[0], 1);
  1128. tscrolldown(term.top, escseq.arg[0]);
  1129. break;
  1130. case 'L': /* IL -- Insert <n> blank lines */
  1131. DEFAULT(escseq.arg[0], 1);
  1132. tinsertblankline(escseq.arg[0]);
  1133. break;
  1134. case 'l': /* RM -- Reset Mode */
  1135. if(escseq.priv) {
  1136. switch(escseq.arg[0]) {
  1137. case 1:
  1138. term.mode &= ~MODE_APPKEYPAD;
  1139. break;
  1140. case 5: /* DECSCNM -- Remove reverse video */
  1141. if(IS_SET(MODE_REVERSE)) {
  1142. term.mode &= ~MODE_REVERSE;
  1143. draw();
  1144. }
  1145. break;
  1146. case 7:
  1147. term.mode &= ~MODE_WRAP;
  1148. break;
  1149. case 12: /* att610 -- Stop blinking cursor (IGNORED) */
  1150. break;
  1151. case 20:
  1152. term.mode &= ~MODE_CRLF;
  1153. break;
  1154. case 25:
  1155. term.c.state |= CURSOR_HIDE;
  1156. break;
  1157. case 1000: /* disable X11 xterm mouse reporting */
  1158. term.mode &= ~MODE_MOUSEBTN;
  1159. break;
  1160. case 1002:
  1161. term.mode &= ~MODE_MOUSEMOTION;
  1162. break;
  1163. case 1049: /* = 1047 and 1048 */
  1164. case 47:
  1165. case 1047:
  1166. if(IS_SET(MODE_ALTSCREEN)) {
  1167. tclearregion(0, 0, term.col-1, term.row-1);
  1168. tswapscreen();
  1169. }
  1170. if(escseq.arg[0] != 1049)
  1171. break;
  1172. case 1048:
  1173. tcursor(CURSOR_LOAD);
  1174. break;
  1175. default:
  1176. goto unknown;
  1177. }
  1178. } else {
  1179. switch(escseq.arg[0]) {
  1180. case 4:
  1181. term.mode &= ~MODE_INSERT;
  1182. break;
  1183. default:
  1184. goto unknown;
  1185. }
  1186. }
  1187. break;
  1188. case 'M': /* DL -- Delete <n> lines */
  1189. DEFAULT(escseq.arg[0], 1);
  1190. tdeleteline(escseq.arg[0]);
  1191. break;
  1192. case 'X': /* ECH -- Erase <n> char */
  1193. DEFAULT(escseq.arg[0], 1);
  1194. tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
  1195. break;
  1196. case 'P': /* DCH -- Delete <n> char */
  1197. DEFAULT(escseq.arg[0], 1);
  1198. tdeletechar(escseq.arg[0]);
  1199. break;
  1200. /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
  1201. case 'd': /* VPA -- Move to <row> */
  1202. DEFAULT(escseq.arg[0], 1);
  1203. tmoveto(term.c.x, escseq.arg[0]-1);
  1204. break;
  1205. case 'h': /* SM -- Set terminal mode */
  1206. if(escseq.priv) {
  1207. switch(escseq.arg[0]) {
  1208. case 1:
  1209. term.mode |= MODE_APPKEYPAD;
  1210. break;
  1211. case 5: /* DECSCNM -- Reverve video */
  1212. if(!IS_SET(MODE_REVERSE)) {
  1213. term.mode |= MODE_REVERSE;
  1214. draw();
  1215. }
  1216. break;
  1217. case 7:
  1218. term.mode |= MODE_WRAP;
  1219. break;
  1220. case 20:
  1221. term.mode |= MODE_CRLF;
  1222. break;
  1223. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1224. /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
  1225. if(escseq.narg > 1 && escseq.arg[1] != 25)
  1226. break;
  1227. case 25:
  1228. term.c.state &= ~CURSOR_HIDE;
  1229. break;
  1230. case 1000: /* 1000,1002: enable xterm mouse report */
  1231. term.mode |= MODE_MOUSEBTN;
  1232. break;
  1233. case 1002:
  1234. term.mode |= MODE_MOUSEMOTION;
  1235. break;
  1236. case 1049: /* = 1047 and 1048 */
  1237. case 47:
  1238. case 1047:
  1239. if(IS_SET(MODE_ALTSCREEN))
  1240. tclearregion(0, 0, term.col-1, term.row-1);
  1241. else
  1242. tswapscreen();
  1243. if(escseq.arg[0] != 1049)
  1244. break;
  1245. case 1048:
  1246. tcursor(CURSOR_SAVE);
  1247. break;
  1248. default: goto unknown;
  1249. }
  1250. } else {
  1251. switch(escseq.arg[0]) {
  1252. case 4:
  1253. term.mode |= MODE_INSERT;
  1254. break;
  1255. default: goto unknown;
  1256. }
  1257. };
  1258. break;
  1259. case 'm': /* SGR -- Terminal attribute (color) */
  1260. tsetattr(escseq.arg, escseq.narg);
  1261. break;
  1262. case 'r': /* DECSTBM -- Set Scrolling Region */
  1263. if(escseq.priv)
  1264. goto unknown;
  1265. else {
  1266. DEFAULT(escseq.arg[0], 1);
  1267. DEFAULT(escseq.arg[1], term.row);
  1268. tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
  1269. tmoveto(0, 0);
  1270. }
  1271. break;
  1272. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1273. tcursor(CURSOR_SAVE);
  1274. break;
  1275. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1276. tcursor(CURSOR_LOAD);
  1277. break;
  1278. }
  1279. }
  1280. void
  1281. csidump(void) {
  1282. int i;
  1283. printf("ESC[");
  1284. for(i = 0; i < escseq.len; i++) {
  1285. uint c = escseq.buf[i] & 0xff;
  1286. if(isprint(c)) putchar(c);
  1287. else if(c == '\n') printf("(\\n)");
  1288. else if(c == '\r') printf("(\\r)");
  1289. else if(c == 0x1b) printf("(\\e)");
  1290. else printf("(%02x)", c);
  1291. }
  1292. putchar('\n');
  1293. }
  1294. void
  1295. csireset(void) {
  1296. memset(&escseq, 0, sizeof(escseq));
  1297. }
  1298. void
  1299. tputtab(void) {
  1300. unsigned x;
  1301. for (x = term.c.x + 1; x < term.col && !term.tabs[x]; ++x)
  1302. /* nothing */ ;
  1303. tmoveto(x, term.c.y);
  1304. }
  1305. void
  1306. tputc(char *c) {
  1307. char ascii = *c;
  1308. if(term.esc & ESC_START) {
  1309. if(term.esc & ESC_CSI) {
  1310. escseq.buf[escseq.len++] = ascii;
  1311. if(BETWEEN(ascii, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
  1312. term.esc = 0;
  1313. csiparse(), csihandle();
  1314. }
  1315. /* TODO: handle other OSC */
  1316. } else if(term.esc & ESC_OSC) {
  1317. if(ascii == ';') {
  1318. term.titlelen = 0;
  1319. term.esc = ESC_START | ESC_TITLE;
  1320. }
  1321. } else if(term.esc & ESC_TITLE) {
  1322. if(ascii == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
  1323. term.esc = 0;
  1324. term.title[term.titlelen] = '\0';
  1325. XStoreName(xw.dpy, xw.win, term.title);
  1326. } else {
  1327. term.title[term.titlelen++] = ascii;
  1328. }
  1329. } else if(term.esc & ESC_ALTCHARSET) {
  1330. switch(ascii) {
  1331. case '0': /* Line drawing crap */
  1332. term.c.attr.mode |= ATTR_GFX;
  1333. break;
  1334. case 'B': /* Back to regular text */
  1335. term.c.attr.mode &= ~ATTR_GFX;
  1336. break;
  1337. default:
  1338. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1339. }
  1340. term.esc = 0;
  1341. } else {
  1342. switch(ascii) {
  1343. case '[':
  1344. term.esc |= ESC_CSI;
  1345. break;
  1346. case ']':
  1347. term.esc |= ESC_OSC;
  1348. break;
  1349. case '(':
  1350. term.esc |= ESC_ALTCHARSET;
  1351. break;
  1352. case 'D': /* IND -- Linefeed */
  1353. if(term.c.y == term.bot)
  1354. tscrollup(term.top, 1);
  1355. else
  1356. tmoveto(term.c.x, term.c.y+1);
  1357. term.esc = 0;
  1358. break;
  1359. case 'E': /* NEL -- Next line */
  1360. tnewline(1); /* always go to first col */
  1361. term.esc = 0;
  1362. break;
  1363. case 'H': /* HTS -- Horizontal tab stop */
  1364. term.tabs[term.c.x] = 1;
  1365. term.esc = 0;
  1366. break;
  1367. case 'M': /* RI -- Reverse index */
  1368. if(term.c.y == term.top)
  1369. tscrolldown(term.top, 1);
  1370. else
  1371. tmoveto(term.c.x, term.c.y-1);
  1372. term.esc = 0;
  1373. break;
  1374. case 'c': /* RIS -- Reset to inital state */
  1375. treset();
  1376. term.esc = 0;
  1377. break;
  1378. case '=': /* DECPAM -- Application keypad */
  1379. term.mode |= MODE_APPKEYPAD;
  1380. term.esc = 0;
  1381. break;
  1382. case '>': /* DECPNM -- Normal keypad */
  1383. term.mode &= ~MODE_APPKEYPAD;
  1384. term.esc = 0;
  1385. break;
  1386. case '7': /* DECSC -- Save Cursor */
  1387. tcursor(CURSOR_SAVE);
  1388. term.esc = 0;
  1389. break;
  1390. case '8': /* DECRC -- Restore Cursor */
  1391. tcursor(CURSOR_LOAD);
  1392. term.esc = 0;
  1393. break;
  1394. default:
  1395. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1396. (uchar) ascii, isprint(ascii)?ascii:'.');
  1397. term.esc = 0;
  1398. }
  1399. }
  1400. } else {
  1401. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1402. sel.bx = -1;
  1403. switch(ascii) {
  1404. case '\t':
  1405. tputtab();
  1406. break;
  1407. case '\b':
  1408. tmoveto(term.c.x-1, term.c.y);
  1409. break;
  1410. case '\r':
  1411. tmoveto(0, term.c.y);
  1412. break;
  1413. case '\f':
  1414. case '\v':
  1415. case '\n':
  1416. /* go to first col if the mode is set */
  1417. tnewline(IS_SET(MODE_CRLF));
  1418. break;
  1419. case '\a':
  1420. if(!(xw.state & WIN_FOCUSED))
  1421. xseturgency(1);
  1422. break;
  1423. case '\033':
  1424. csireset();
  1425. term.esc = ESC_START;
  1426. break;
  1427. default:
  1428. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1429. tnewline(1); /* always go to first col */
  1430. tsetchar(c);
  1431. if(term.c.x+1 < term.col)
  1432. tmoveto(term.c.x+1, term.c.y);
  1433. else
  1434. term.c.state |= CURSOR_WRAPNEXT;
  1435. }
  1436. }
  1437. }
  1438. int
  1439. tresize(int col, int row) {
  1440. int i, x;
  1441. int minrow = MIN(row, term.row);
  1442. int mincol = MIN(col, term.col);
  1443. int slide = term.c.y - row + 1;
  1444. if(col < 1 || row < 1)
  1445. return 0;
  1446. /* free unneeded rows */
  1447. i = 0;
  1448. if(slide > 0) {
  1449. /* slide screen to keep cursor where we expect it -
  1450. * tscrollup would work here, but we can optimize to
  1451. * memmove because we're freeing the earlier lines */
  1452. for(/* i = 0 */; i < slide; i++) {
  1453. free(term.line[i]);
  1454. free(term.alt[i]);
  1455. }
  1456. memmove(term.line, term.line + slide, row * sizeof(Line));
  1457. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1458. }
  1459. for(i += row; i < term.row; i++) {
  1460. free(term.line[i]);
  1461. free(term.alt[i]);
  1462. }
  1463. /* resize to new height */
  1464. term.line = realloc(term.line, row * sizeof(Line));
  1465. term.alt = realloc(term.alt, row * sizeof(Line));
  1466. term.dirty = realloc(term.dirty, row * sizeof(*term.dirty));
  1467. term.tabs = realloc(term.tabs, col * sizeof(*term.tabs));
  1468. /* resize each row to new width, zero-pad if needed */
  1469. for(i = 0; i < minrow; i++) {
  1470. term.dirty[i] = 1;
  1471. term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
  1472. term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
  1473. for(x = mincol; x < col; x++) {
  1474. term.line[i][x].state = 0;
  1475. term.alt[i][x].state = 0;
  1476. }
  1477. }
  1478. /* allocate any new rows */
  1479. for(/* i == minrow */; i < row; i++) {
  1480. term.dirty[i] = 1;
  1481. term.line[i] = calloc(col, sizeof(Glyph));
  1482. term.alt [i] = calloc(col, sizeof(Glyph));
  1483. }
  1484. if (col > term.col) {
  1485. bool *bp = term.tabs + term.col;
  1486. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1487. while (--bp > term.tabs && !*bp)
  1488. /* nothing */ ;
  1489. for (bp += TAB; bp < term.tabs + col; bp += TAB)
  1490. *bp = 1;
  1491. }
  1492. /* update terminal size */
  1493. term.col = col, term.row = row;
  1494. /* make use of the LIMIT in tmoveto */
  1495. tmoveto(term.c.x, term.c.y);
  1496. /* reset scrolling region */
  1497. tsetscroll(0, row-1);
  1498. return (slide > 0);
  1499. }
  1500. void
  1501. xresize(int col, int row) {
  1502. xw.w = MAX(1, 2*BORDER + col * xw.cw);
  1503. xw.h = MAX(1, 2*BORDER + row * xw.ch);
  1504. }
  1505. void
  1506. xloadcols(void) {
  1507. int i, r, g, b;
  1508. XColor color;
  1509. ulong white = WhitePixel(xw.dpy, xw.scr);
  1510. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1511. for(i = 0; i < LEN(colorname); i++) {
  1512. if(!colorname[i])
  1513. continue;
  1514. if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
  1515. dc.col[i] = white;
  1516. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1517. } else
  1518. dc.col[i] = color.pixel;
  1519. }
  1520. /* load colors [16-255] ; same colors as xterm */
  1521. for(i = 16, r = 0; r < 6; r++)
  1522. for(g = 0; g < 6; g++)
  1523. for(b = 0; b < 6; b++) {
  1524. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1525. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1526. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1527. if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1528. dc.col[i] = white;
  1529. fprintf(stderr, "Could not allocate color %d\n", i);
  1530. } else
  1531. dc.col[i] = color.pixel;
  1532. i++;
  1533. }
  1534. for(r = 0; r < 24; r++, i++) {
  1535. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1536. if (!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1537. dc.col[i] = white;
  1538. fprintf(stderr, "Could not allocate color %d\n", i);
  1539. } else
  1540. dc.col[i] = color.pixel;
  1541. }
  1542. }
  1543. void
  1544. xclear(int x1, int y1, int x2, int y2) {
  1545. XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
  1546. XFillRectangle(xw.dpy, xw.buf, dc.gc,
  1547. BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
  1548. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1549. }
  1550. void
  1551. xhints(void) {
  1552. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1553. XWMHints wm = {.flags = InputHint, .input = 1};
  1554. XSizeHints size = {
  1555. .flags = PSize | PResizeInc | PBaseSize,
  1556. .height = xw.h,
  1557. .width = xw.w,
  1558. .height_inc = xw.ch,
  1559. .width_inc = xw.cw,
  1560. .base_height = 2*BORDER,
  1561. .base_width = 2*BORDER,
  1562. };
  1563. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
  1564. }
  1565. XFontSet
  1566. xinitfont(char *fontstr) {
  1567. XFontSet set;
  1568. char *def, **missing;
  1569. int n;
  1570. missing = NULL;
  1571. set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
  1572. if(missing) {
  1573. while(n--)
  1574. fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
  1575. XFreeStringList(missing);
  1576. }
  1577. return set;
  1578. }
  1579. void
  1580. xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
  1581. XFontStruct **xfonts;
  1582. char **font_names;
  1583. int i, n;
  1584. *ascent = *descent = *lbearing = *rbearing = 0;
  1585. n = XFontsOfFontSet(set, &xfonts, &font_names);
  1586. for(i = 0; i < n; i++) {
  1587. *ascent = MAX(*ascent, (*xfonts)->ascent);
  1588. *descent = MAX(*descent, (*xfonts)->descent);
  1589. *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
  1590. *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
  1591. xfonts++;
  1592. }
  1593. }
  1594. void
  1595. initfonts(char *fontstr, char *bfontstr) {
  1596. if((dc.font.set = xinitfont(fontstr)) == NULL ||
  1597. (dc.bfont.set = xinitfont(bfontstr)) == NULL)
  1598. die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
  1599. xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
  1600. &dc.font.lbearing, &dc.font.rbearing);
  1601. xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
  1602. &dc.bfont.lbearing, &dc.bfont.rbearing);
  1603. }
  1604. void
  1605. xinit(void) {
  1606. XSetWindowAttributes attrs;
  1607. Cursor cursor;
  1608. Window parent;
  1609. if(!(xw.dpy = XOpenDisplay(NULL)))
  1610. die("Can't open display\n");
  1611. xw.scr = XDefaultScreen(xw.dpy);
  1612. /* font */
  1613. initfonts(FONT, BOLDFONT);
  1614. /* XXX: Assuming same size for bold font */
  1615. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1616. xw.ch = dc.font.ascent + dc.font.descent;
  1617. /* colors */
  1618. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1619. xloadcols();
  1620. /* window - default size */
  1621. xw.h = 2*BORDER + term.row * xw.ch;
  1622. xw.w = 2*BORDER + term.col * xw.cw;
  1623. attrs.background_pixel = dc.col[DefaultBG];
  1624. attrs.border_pixel = dc.col[DefaultBG];
  1625. attrs.bit_gravity = NorthWestGravity;
  1626. attrs.event_mask = FocusChangeMask | KeyPressMask
  1627. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1628. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask
  1629. | EnterWindowMask | LeaveWindowMask;
  1630. attrs.colormap = xw.cmap;
  1631. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  1632. xw.win = XCreateWindow(xw.dpy, parent, 0, 0,
  1633. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1634. XDefaultVisual(xw.dpy, xw.scr),
  1635. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1636. | CWColormap,
  1637. &attrs);
  1638. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  1639. /* input methods */
  1640. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1641. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1642. | XIMStatusNothing, XNClientWindow, xw.win,
  1643. XNFocusWindow, xw.win, NULL);
  1644. /* gc */
  1645. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1646. /* white cursor, black outline */
  1647. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1648. XDefineCursor(xw.dpy, xw.win, cursor);
  1649. XRecolorCursor(xw.dpy, cursor,
  1650. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1651. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1652. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1653. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1654. XMapWindow(xw.dpy, xw.win);
  1655. xhints();
  1656. XSync(xw.dpy, 0);
  1657. }
  1658. void
  1659. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1660. int fg = base.fg, bg = base.bg, temp;
  1661. int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1662. XFontSet fontset = dc.font.set;
  1663. int i;
  1664. /* only switch default fg/bg if term is in RV mode */
  1665. if(IS_SET(MODE_REVERSE)) {
  1666. if(fg == DefaultFG)
  1667. fg = DefaultBG;
  1668. if(bg == DefaultBG)
  1669. bg = DefaultFG;
  1670. }
  1671. if(base.mode & ATTR_REVERSE)
  1672. temp = fg, fg = bg, bg = temp;
  1673. if(base.mode & ATTR_BOLD) {
  1674. fg += 8;
  1675. fontset = dc.bfont.set;
  1676. }
  1677. XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
  1678. XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
  1679. if(base.mode & ATTR_GFX) {
  1680. for(i = 0; i < bytelen; i++) {
  1681. char c = gfx[(uint)s[i] % 256];
  1682. if(c)
  1683. s[i] = c;
  1684. else if(s[i] > 0x5f)
  1685. s[i] -= 0x5f;
  1686. }
  1687. }
  1688. XmbDrawImageString(xw.dpy, xw.buf, fontset, dc.gc, winx, winy, s, bytelen);
  1689. if(base.mode & ATTR_UNDERLINE)
  1690. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1691. }
  1692. /* copy buffer pixmap to screen pixmap */
  1693. void
  1694. xcopy() {
  1695. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  1696. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  1697. }
  1698. void
  1699. xdrawcursor(void) {
  1700. static int oldx = 0;
  1701. static int oldy = 0;
  1702. int sl;
  1703. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1704. LIMIT(oldx, 0, term.col-1);
  1705. LIMIT(oldy, 0, term.row-1);
  1706. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1707. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1708. /* remove the old cursor */
  1709. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1710. sl = utf8size(term.line[oldy][oldx].c);
  1711. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1712. } else
  1713. xclear(oldx, oldy, oldx, oldy);
  1714. xcopy(oldx, oldy, 1, 1);
  1715. /* draw the new one */
  1716. if(!(term.c.state & CURSOR_HIDE)) {
  1717. if(!(xw.state & WIN_FOCUSED))
  1718. g.bg = DefaultUCS;
  1719. if(IS_SET(MODE_REVERSE))
  1720. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  1721. sl = utf8size(g.c);
  1722. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1723. oldx = term.c.x, oldy = term.c.y;
  1724. }
  1725. xcopy(term.c.x, term.c.y, 1, 1);
  1726. }
  1727. void
  1728. draw() {
  1729. drawregion(0, 0, term.col, term.row);
  1730. xcopy();
  1731. gettimeofday(&xw.lastdraw, NULL);
  1732. }
  1733. void
  1734. drawregion(int x1, int y1, int x2, int y2) {
  1735. int ic, ib, x, y, ox, sl;
  1736. Glyph base, new;
  1737. char buf[DRAW_BUF_SIZ];
  1738. if(!(xw.state & WIN_VISIBLE))
  1739. return;
  1740. for(y = y1; y < y2; y++) {
  1741. if(!term.dirty[y])
  1742. continue;
  1743. xclear(0, y, term.col, y);
  1744. term.dirty[y] = 0;
  1745. base = term.line[y][0];
  1746. ic = ib = ox = 0;
  1747. for(x = x1; x < x2; x++) {
  1748. new = term.line[y][x];
  1749. if(sel.bx != -1 && *(new.c) && selected(x, y))
  1750. new.mode ^= ATTR_REVERSE;
  1751. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1752. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1753. xdraws(buf, base, ox, y, ic, ib);
  1754. ic = ib = 0;
  1755. }
  1756. if(new.state & GLYPH_SET) {
  1757. if(ib == 0) {
  1758. ox = x;
  1759. base = new;
  1760. }
  1761. sl = utf8size(new.c);
  1762. memcpy(buf+ib, new.c, sl);
  1763. ib += sl;
  1764. ++ic;
  1765. }
  1766. }
  1767. if(ib > 0)
  1768. xdraws(buf, base, ox, y, ic, ib);
  1769. }
  1770. xdrawcursor();
  1771. }
  1772. void
  1773. expose(XEvent *ev) {
  1774. XExposeEvent *e = &ev->xexpose;
  1775. if(xw.state & WIN_REDRAW) {
  1776. if(!e->count)
  1777. xw.state &= ~WIN_REDRAW;
  1778. }
  1779. xcopy();
  1780. }
  1781. void
  1782. visibility(XEvent *ev) {
  1783. XVisibilityEvent *e = &ev->xvisibility;
  1784. if(e->state == VisibilityFullyObscured)
  1785. xw.state &= ~WIN_VISIBLE;
  1786. else if(!(xw.state & WIN_VISIBLE))
  1787. /* need a full redraw for next Expose, not just a buf copy */
  1788. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1789. }
  1790. void
  1791. unmap(XEvent *ev) {
  1792. xw.state &= ~WIN_VISIBLE;
  1793. }
  1794. void
  1795. xseturgency(int add) {
  1796. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1797. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1798. XSetWMHints(xw.dpy, xw.win, h);
  1799. XFree(h);
  1800. }
  1801. void
  1802. focus(XEvent *ev) {
  1803. if(ev->type == FocusIn) {
  1804. xw.state |= WIN_FOCUSED;
  1805. xseturgency(0);
  1806. } else
  1807. xw.state &= ~WIN_FOCUSED;
  1808. draw();
  1809. }
  1810. char*
  1811. kmap(KeySym k, uint state) {
  1812. int i;
  1813. state &= ~Mod2Mask;
  1814. for(i = 0; i < LEN(key); i++) {
  1815. uint mask = key[i].mask;
  1816. if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
  1817. return (char*)key[i].s;
  1818. }
  1819. return NULL;
  1820. }
  1821. void
  1822. kpress(XEvent *ev) {
  1823. XKeyEvent *e = &ev->xkey;
  1824. KeySym ksym;
  1825. char buf[32];
  1826. char *customkey;
  1827. int len;
  1828. int meta;
  1829. int shift;
  1830. Status status;
  1831. meta = e->state & Mod1Mask;
  1832. shift = e->state & ShiftMask;
  1833. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1834. /* 1. custom keys from config.h */
  1835. if((customkey = kmap(ksym, e->state)))
  1836. ttywrite(customkey, strlen(customkey));
  1837. /* 2. hardcoded (overrides X lookup) */
  1838. else
  1839. switch(ksym) {
  1840. case XK_Up:
  1841. case XK_Down:
  1842. case XK_Left:
  1843. case XK_Right:
  1844. /* XXX: shift up/down doesn't work */
  1845. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
  1846. ttywrite(buf, 3);
  1847. break;
  1848. case XK_Insert:
  1849. if(shift)
  1850. selpaste();
  1851. break;
  1852. case XK_Return:
  1853. if(IS_SET(MODE_CRLF))
  1854. ttywrite("\r\n", 2);
  1855. else
  1856. ttywrite("\r", 1);
  1857. break;
  1858. /* 3. X lookup */
  1859. default:
  1860. if(len > 0) {
  1861. if(meta && len == 1)
  1862. ttywrite("\033", 1);
  1863. ttywrite(buf, len);
  1864. }
  1865. break;
  1866. }
  1867. }
  1868. void
  1869. cmessage(XEvent *e) {
  1870. /* See xembed specs
  1871. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  1872. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1873. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1874. xw.state |= WIN_FOCUSED;
  1875. xseturgency(0);
  1876. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1877. xw.state &= ~WIN_FOCUSED;
  1878. }
  1879. draw();
  1880. }
  1881. }
  1882. void
  1883. resize(XEvent *e) {
  1884. int col, row;
  1885. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  1886. return;
  1887. xw.w = e->xconfigure.width;
  1888. xw.h = e->xconfigure.height;
  1889. col = (xw.w - 2*BORDER) / xw.cw;
  1890. row = (xw.h - 2*BORDER) / xw.ch;
  1891. if(col == term.col && row == term.row)
  1892. return;
  1893. if(tresize(col, row))
  1894. draw();
  1895. ttyresize(col, row);
  1896. xresize(col, row);
  1897. }
  1898. bool
  1899. last_draw_too_old(void) {
  1900. struct timeval now;
  1901. gettimeofday(&now, NULL);
  1902. return TIMEDIFF(now, xw.lastdraw) >= DRAW_TIMEOUT/1000;
  1903. }
  1904. void
  1905. run(void) {
  1906. XEvent ev;
  1907. fd_set rfd;
  1908. int xfd = XConnectionNumber(xw.dpy);
  1909. struct timeval timeout = {0};
  1910. bool stuff_to_print = 0;
  1911. for(;;) {
  1912. FD_ZERO(&rfd);
  1913. FD_SET(cmdfd, &rfd);
  1914. FD_SET(xfd, &rfd);
  1915. timeout.tv_sec = 0;
  1916. timeout.tv_usec = SELECT_TIMEOUT;
  1917. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, &timeout) < 0) {
  1918. if(errno == EINTR)
  1919. continue;
  1920. die("select failed: %s\n", SERRNO);
  1921. }
  1922. if(FD_ISSET(cmdfd, &rfd)) {
  1923. ttyread();
  1924. stuff_to_print = 1;
  1925. }
  1926. if(stuff_to_print && last_draw_too_old()) {
  1927. stuff_to_print = 0;
  1928. draw();
  1929. }
  1930. while(XPending(xw.dpy)) {
  1931. XNextEvent(xw.dpy, &ev);
  1932. if(XFilterEvent(&ev, xw.win))
  1933. continue;
  1934. if(handler[ev.type])
  1935. (handler[ev.type])(&ev);
  1936. }
  1937. }
  1938. }
  1939. int
  1940. main(int argc, char *argv[]) {
  1941. int i;
  1942. for(i = 1; i < argc; i++) {
  1943. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  1944. case 't':
  1945. if(++i < argc) opt_title = argv[i];
  1946. break;
  1947. case 'c':
  1948. if(++i < argc) opt_class = argv[i];
  1949. break;
  1950. case 'w':
  1951. if(++i < argc) opt_embed = argv[i];
  1952. break;
  1953. case 'e':
  1954. /* eat every remaining arguments */
  1955. if(++i < argc) opt_cmd = &argv[i];
  1956. goto run;
  1957. case 'v':
  1958. default:
  1959. die(USAGE);
  1960. }
  1961. }
  1962. run:
  1963. setlocale(LC_CTYPE, "");
  1964. tnew(80, 24);
  1965. ttynew();
  1966. xinit();
  1967. selinit();
  1968. run();
  1969. return 0;
  1970. }