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.

2163 lines
48 KiB

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