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.

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