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.

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