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.

2111 lines
48 KiB

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