Simple Terminal from SuckLess
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.

2106 lines
48 KiB

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