My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2940 lines
64 KiB

13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
15 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
12 years ago
14 years ago
14 years ago
14 years ago
14 years ago
  1. /* See LICENSE for licence details. */
  2. #define _XOPEN_SOURCE 600
  3. #include <ctype.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <limits.h>
  7. #include <locale.h>
  8. #include <pwd.h>
  9. #include <stdarg.h>
  10. #include <stdbool.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <signal.h>
  15. #include <sys/ioctl.h>
  16. #include <sys/select.h>
  17. #include <sys/stat.h>
  18. #include <sys/time.h>
  19. #include <sys/types.h>
  20. #include <sys/wait.h>
  21. #include <time.h>
  22. #include <unistd.h>
  23. #include <X11/Xatom.h>
  24. #include <X11/Xlib.h>
  25. #include <X11/Xutil.h>
  26. #include <X11/cursorfont.h>
  27. #include <X11/keysym.h>
  28. #include <X11/extensions/Xdbe.h>
  29. #include <X11/Xft/Xft.h>
  30. #include <fontconfig/fontconfig.h>
  31. #define Glyph Glyph_
  32. #define Font Font_
  33. #define Draw XftDraw *
  34. #define Colour XftColor
  35. #define Colourmap Colormap
  36. #if defined(__linux)
  37. #include <pty.h>
  38. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  39. #include <util.h>
  40. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  41. #include <libutil.h>
  42. #endif
  43. #define USAGE \
  44. "st " VERSION " (c) 2010-2012 st engineers\n" \
  45. "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
  46. " [-t title] [-w windowid] [-e command ...]\n"
  47. /* XEMBED messages */
  48. #define XEMBED_FOCUS_IN 4
  49. #define XEMBED_FOCUS_OUT 5
  50. /* Arbitrary sizes */
  51. #define ESC_BUF_SIZ 256
  52. #define ESC_ARG_SIZ 16
  53. #define STR_BUF_SIZ 256
  54. #define STR_ARG_SIZ 16
  55. #define DRAW_BUF_SIZ 20*1024
  56. #define UTF_SIZ 4
  57. #define XK_NO_MOD UINT_MAX
  58. #define XK_ANY_MOD 0
  59. #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
  60. /* macros */
  61. #define CLEANMASK(mask) (mask & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
  62. #define SERRNO strerror(errno)
  63. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  64. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  65. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  66. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  67. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  68. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  69. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  70. #define IS_SET(flag) (term.mode & (flag))
  71. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
  72. #define VT102ID "\033[?6c"
  73. enum glyph_attribute {
  74. ATTR_NULL = 0,
  75. ATTR_REVERSE = 1,
  76. ATTR_UNDERLINE = 2,
  77. ATTR_BOLD = 4,
  78. ATTR_GFX = 8,
  79. ATTR_ITALIC = 16,
  80. ATTR_BLINK = 32,
  81. };
  82. enum cursor_movement {
  83. CURSOR_UP,
  84. CURSOR_DOWN,
  85. CURSOR_LEFT,
  86. CURSOR_RIGHT,
  87. CURSOR_SAVE,
  88. CURSOR_LOAD
  89. };
  90. enum cursor_state {
  91. CURSOR_DEFAULT = 0,
  92. CURSOR_WRAPNEXT = 1,
  93. CURSOR_ORIGIN = 2
  94. };
  95. enum glyph_state {
  96. GLYPH_SET = 1,
  97. GLYPH_DIRTY = 2
  98. };
  99. enum term_mode {
  100. MODE_WRAP = 1,
  101. MODE_INSERT = 2,
  102. MODE_APPKEYPAD = 4,
  103. MODE_ALTSCREEN = 8,
  104. MODE_CRLF = 16,
  105. MODE_MOUSEBTN = 32,
  106. MODE_MOUSEMOTION = 64,
  107. MODE_MOUSE = 32|64,
  108. MODE_REVERSE = 128,
  109. MODE_KBDLOCK = 256,
  110. MODE_HIDE = 512,
  111. MODE_ECHO = 1024,
  112. MODE_APPCURSOR = 2048
  113. };
  114. enum escape_state {
  115. ESC_START = 1,
  116. ESC_CSI = 2,
  117. ESC_STR = 4, /* DSC, OSC, PM, APC */
  118. ESC_ALTCHARSET = 8,
  119. ESC_STR_END = 16, /* a final string was encountered */
  120. ESC_TEST = 32, /* Enter in test mode */
  121. };
  122. enum window_state {
  123. WIN_VISIBLE = 1,
  124. WIN_REDRAW = 2,
  125. WIN_FOCUSED = 4
  126. };
  127. /* bit macro */
  128. #undef B0
  129. enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
  130. typedef unsigned char uchar;
  131. typedef unsigned int uint;
  132. typedef unsigned long ulong;
  133. typedef unsigned short ushort;
  134. typedef struct {
  135. char c[UTF_SIZ]; /* character code */
  136. uchar mode; /* attribute flags */
  137. ushort fg; /* foreground */
  138. ushort bg; /* background */
  139. uchar state; /* state flags */
  140. } Glyph;
  141. typedef Glyph* Line;
  142. typedef struct {
  143. Glyph attr; /* current char attributes */
  144. int x;
  145. int y;
  146. char state;
  147. } TCursor;
  148. /* CSI Escape sequence structs */
  149. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  150. typedef struct {
  151. char buf[ESC_BUF_SIZ]; /* raw string */
  152. int len; /* raw string length */
  153. char priv;
  154. int arg[ESC_ARG_SIZ];
  155. int narg; /* nb of args */
  156. char mode;
  157. } CSIEscape;
  158. /* STR Escape sequence structs */
  159. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  160. typedef struct {
  161. char type; /* ESC type ... */
  162. char buf[STR_BUF_SIZ]; /* raw string */
  163. int len; /* raw string length */
  164. char *args[STR_ARG_SIZ];
  165. int narg; /* nb of args */
  166. } STREscape;
  167. /* Internal representation of the screen */
  168. typedef struct {
  169. int row; /* nb row */
  170. int col; /* nb col */
  171. Line *line; /* screen */
  172. Line *alt; /* alternate screen */
  173. bool *dirty; /* dirtyness of lines */
  174. TCursor c; /* cursor */
  175. int top; /* top scroll limit */
  176. int bot; /* bottom scroll limit */
  177. int mode; /* terminal mode flags */
  178. int esc; /* escape state flags */
  179. bool *tabs;
  180. } Term;
  181. /* Purely graphic info */
  182. typedef struct {
  183. Display *dpy;
  184. Colourmap cmap;
  185. Window win;
  186. XdbeBackBuffer buf;
  187. Atom xembed, wmdeletewin;
  188. XIM xim;
  189. XIC xic;
  190. Draw draw;
  191. Visual *vis;
  192. int scr;
  193. bool isfixed; /* is fixed geometry? */
  194. int fx, fy, fw, fh; /* fixed geometry */
  195. int tw, th; /* tty width and height */
  196. int w; /* window width */
  197. int h; /* window height */
  198. int ch; /* char height */
  199. int cw; /* char width */
  200. char state; /* focus, redraw, visible */
  201. } XWindow;
  202. typedef struct {
  203. KeySym k;
  204. uint mask;
  205. char s[ESC_BUF_SIZ];
  206. /* three valued logic variables: 0 indifferent, 1 on, -1 off */
  207. signed char appkey; /* application keypad */
  208. signed char appcursor; /* application cursor */
  209. signed char crlf; /* crlf mode */
  210. } Key;
  211. /* TODO: use better name for vars... */
  212. typedef struct {
  213. int mode;
  214. int bx, by;
  215. int ex, ey;
  216. struct {
  217. int x, y;
  218. } b, e;
  219. char *clip;
  220. Atom xtarget;
  221. bool alt;
  222. struct timeval tclick1;
  223. struct timeval tclick2;
  224. } Selection;
  225. typedef union {
  226. int i;
  227. unsigned int ui;
  228. float f;
  229. const void *v;
  230. } Arg;
  231. typedef struct {
  232. unsigned int mod;
  233. KeySym keysym;
  234. void (*func)(const Arg *);
  235. const Arg arg;
  236. } Shortcut;
  237. /* function definitions used in config.h */
  238. static void xzoom(const Arg *);
  239. static void selpaste(const Arg *);
  240. /* Config.h for applying patches and the configuration. */
  241. #include "config.h"
  242. /* Font structure */
  243. typedef struct {
  244. int height;
  245. int width;
  246. int ascent;
  247. int descent;
  248. short lbearing;
  249. short rbearing;
  250. XftFont *set;
  251. } Font;
  252. /* Drawing Context */
  253. typedef struct {
  254. Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
  255. Font font, bfont, ifont, ibfont;
  256. } DC;
  257. static void die(const char *, ...);
  258. static void draw(void);
  259. static void redraw(void);
  260. static void drawregion(int, int, int, int);
  261. static void execsh(void);
  262. static void sigchld(int);
  263. static void run(void);
  264. static void csidump(void);
  265. static void csihandle(void);
  266. static void csiparse(void);
  267. static void csireset(void);
  268. static void strdump(void);
  269. static void strhandle(void);
  270. static void strparse(void);
  271. static void strreset(void);
  272. static void tclearregion(int, int, int, int);
  273. static void tcursor(int);
  274. static void tdeletechar(int);
  275. static void tdeleteline(int);
  276. static void tinsertblank(int);
  277. static void tinsertblankline(int);
  278. static void tmoveto(int, int);
  279. static void tmoveato(int x, int y);
  280. static void tnew(int, int);
  281. static void tnewline(int);
  282. static void tputtab(bool);
  283. static void tputc(char *, int);
  284. static void treset(void);
  285. static int tresize(int, int);
  286. static void tscrollup(int, int);
  287. static void tscrolldown(int, int);
  288. static void tsetattr(int*, int);
  289. static void tsetchar(char *, Glyph *, int, int);
  290. static void tsetscroll(int, int);
  291. static void tswapscreen(void);
  292. static void tsetdirt(int, int);
  293. static void tsetmode(bool, bool, int *, int);
  294. static void tfulldirt(void);
  295. static void techo(char *, int);
  296. static void ttynew(void);
  297. static void ttyread(void);
  298. static void ttyresize(void);
  299. static void ttywrite(const char *, size_t);
  300. static void xdraws(char *, Glyph, int, int, int, int);
  301. static void xhints(void);
  302. static void xclear(int, int, int, int);
  303. static void xdrawcursor(void);
  304. static void xinit(void);
  305. static void xloadcols(void);
  306. static void xresettitle(void);
  307. static void xseturgency(int);
  308. static void xsetsel(char*);
  309. static void xtermclear(int, int, int, int);
  310. static void xresize(int, int);
  311. static void expose(XEvent *);
  312. static void visibility(XEvent *);
  313. static void unmap(XEvent *);
  314. static char *kmap(KeySym, uint);
  315. static void kpress(XEvent *);
  316. static void cmessage(XEvent *);
  317. static void cresize(int width, int height);
  318. static void resize(XEvent *);
  319. static void focus(XEvent *);
  320. static void brelease(XEvent *);
  321. static void bpress(XEvent *);
  322. static void bmotion(XEvent *);
  323. static void selnotify(XEvent *);
  324. static void selclear(XEvent *);
  325. static void selrequest(XEvent *);
  326. static void selinit(void);
  327. static inline bool selected(int, int);
  328. static void selcopy(void);
  329. static void selscroll(int, int);
  330. static int utf8decode(char *, long *);
  331. static int utf8encode(long *, char *);
  332. static int utf8size(char *);
  333. static int isfullutf8(char *, int);
  334. static ssize_t xwrite(int, char *, size_t);
  335. static void *xmalloc(size_t);
  336. static void *xrealloc(void *, size_t);
  337. static void *xcalloc(size_t nmemb, size_t size);
  338. static void (*handler[LASTEvent])(XEvent *) = {
  339. [KeyPress] = kpress,
  340. [ClientMessage] = cmessage,
  341. [ConfigureNotify] = resize,
  342. [VisibilityNotify] = visibility,
  343. [UnmapNotify] = unmap,
  344. [Expose] = expose,
  345. [FocusIn] = focus,
  346. [FocusOut] = focus,
  347. [MotionNotify] = bmotion,
  348. [ButtonPress] = bpress,
  349. [ButtonRelease] = brelease,
  350. [SelectionClear] = selclear,
  351. [SelectionNotify] = selnotify,
  352. [SelectionRequest] = selrequest,
  353. };
  354. /* Globals */
  355. static DC dc;
  356. static XWindow xw;
  357. static Term term;
  358. static CSIEscape csiescseq;
  359. static STREscape strescseq;
  360. static int cmdfd;
  361. static pid_t pid;
  362. static Selection sel;
  363. static int iofd = -1;
  364. static char **opt_cmd = NULL;
  365. static char *opt_io = NULL;
  366. static char *opt_title = NULL;
  367. static char *opt_embed = NULL;
  368. static char *opt_class = NULL;
  369. static char *opt_font = NULL;
  370. static char *usedfont = NULL;
  371. static int usedfontsize = 0;
  372. ssize_t
  373. xwrite(int fd, char *s, size_t len) {
  374. size_t aux = len;
  375. while(len > 0) {
  376. ssize_t r = write(fd, s, len);
  377. if(r < 0)
  378. return r;
  379. len -= r;
  380. s += r;
  381. }
  382. return aux;
  383. }
  384. void *
  385. xmalloc(size_t len) {
  386. void *p = malloc(len);
  387. if(!p)
  388. die("Out of memory\n");
  389. return p;
  390. }
  391. void *
  392. xrealloc(void *p, size_t len) {
  393. if((p = realloc(p, len)) == NULL)
  394. die("Out of memory\n");
  395. return p;
  396. }
  397. void *
  398. xcalloc(size_t nmemb, size_t size) {
  399. void *p = calloc(nmemb, size);
  400. if(!p)
  401. die("Out of memory\n");
  402. return p;
  403. }
  404. int
  405. utf8decode(char *s, long *u) {
  406. uchar c;
  407. int i, n, rtn;
  408. rtn = 1;
  409. c = *s;
  410. if(~c & B7) { /* 0xxxxxxx */
  411. *u = c;
  412. return rtn;
  413. } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
  414. *u = c&(B4|B3|B2|B1|B0);
  415. n = 1;
  416. } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
  417. *u = c&(B3|B2|B1|B0);
  418. n = 2;
  419. } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
  420. *u = c & (B2|B1|B0);
  421. n = 3;
  422. } else {
  423. goto invalid;
  424. }
  425. for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
  426. c = *s;
  427. if((c & (B7|B6)) != B7) /* 10xxxxxx */
  428. goto invalid;
  429. *u <<= 6;
  430. *u |= c & (B5|B4|B3|B2|B1|B0);
  431. }
  432. if((n == 1 && *u < 0x80) ||
  433. (n == 2 && *u < 0x800) ||
  434. (n == 3 && *u < 0x10000) ||
  435. (*u >= 0xD800 && *u <= 0xDFFF)) {
  436. goto invalid;
  437. }
  438. return rtn;
  439. invalid:
  440. *u = 0xFFFD;
  441. return rtn;
  442. }
  443. int
  444. utf8encode(long *u, char *s) {
  445. uchar *sp;
  446. ulong uc;
  447. int i, n;
  448. sp = (uchar *)s;
  449. uc = *u;
  450. if(uc < 0x80) {
  451. *sp = uc; /* 0xxxxxxx */
  452. return 1;
  453. } else if(*u < 0x800) {
  454. *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
  455. n = 1;
  456. } else if(uc < 0x10000) {
  457. *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
  458. n = 2;
  459. } else if(uc <= 0x10FFFF) {
  460. *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
  461. n = 3;
  462. } else {
  463. goto invalid;
  464. }
  465. for(i=n,++sp; i>0; --i,++sp)
  466. *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
  467. return n+1;
  468. invalid:
  469. /* U+FFFD */
  470. *s++ = '\xEF';
  471. *s++ = '\xBF';
  472. *s = '\xBD';
  473. return 3;
  474. }
  475. /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
  476. UTF-8 otherwise return 0 */
  477. int
  478. isfullutf8(char *s, int b) {
  479. uchar *c1, *c2, *c3;
  480. c1 = (uchar *)s;
  481. c2 = (uchar *)++s;
  482. c3 = (uchar *)++s;
  483. if(b < 1) {
  484. return 0;
  485. } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
  486. return 0;
  487. } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
  488. ((b == 1) ||
  489. ((b == 2) && (*c2&(B7|B6)) == B7))) {
  490. return 0;
  491. } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
  492. ((b == 1) ||
  493. ((b == 2) && (*c2&(B7|B6)) == B7) ||
  494. ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
  495. return 0;
  496. } else {
  497. return 1;
  498. }
  499. }
  500. int
  501. utf8size(char *s) {
  502. uchar c = *s;
  503. if(~c&B7) {
  504. return 1;
  505. } else if((c&(B7|B6|B5)) == (B7|B6)) {
  506. return 2;
  507. } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
  508. return 3;
  509. } else {
  510. return 4;
  511. }
  512. }
  513. void
  514. selinit(void) {
  515. memset(&sel.tclick1, 0, sizeof(sel.tclick1));
  516. memset(&sel.tclick2, 0, sizeof(sel.tclick2));
  517. sel.mode = 0;
  518. sel.bx = -1;
  519. sel.clip = NULL;
  520. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  521. if(sel.xtarget == None)
  522. sel.xtarget = XA_STRING;
  523. }
  524. static int
  525. x2col(int x) {
  526. x -= borderpx;
  527. x /= xw.cw;
  528. return LIMIT(x, 0, term.col-1);
  529. }
  530. static int
  531. y2row(int y) {
  532. y -= borderpx;
  533. y /= xw.ch;
  534. return LIMIT(y, 0, term.row-1);
  535. }
  536. static inline bool
  537. selected(int x, int y) {
  538. int bx, ex;
  539. if(sel.ey == y && sel.by == y) {
  540. bx = MIN(sel.bx, sel.ex);
  541. ex = MAX(sel.bx, sel.ex);
  542. return BETWEEN(x, bx, ex);
  543. }
  544. return ((sel.b.y < y && y < sel.e.y)
  545. || (y == sel.e.y && x <= sel.e.x))
  546. || (y == sel.b.y && x >= sel.b.x
  547. && (x <= sel.e.x || sel.b.y != sel.e.y));
  548. }
  549. void
  550. getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
  551. if(b)
  552. *b = e->xbutton.button;
  553. *x = x2col(e->xbutton.x);
  554. *y = y2row(e->xbutton.y);
  555. sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
  556. sel.b.y = MIN(sel.by, sel.ey);
  557. sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
  558. sel.e.y = MAX(sel.by, sel.ey);
  559. }
  560. void
  561. mousereport(XEvent *e) {
  562. int x = x2col(e->xbutton.x);
  563. int y = y2row(e->xbutton.y);
  564. int button = e->xbutton.button;
  565. int state = e->xbutton.state;
  566. char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
  567. static int ob, ox, oy;
  568. /* from urxvt */
  569. if(e->xbutton.type == MotionNotify) {
  570. if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
  571. return;
  572. button = ob + 32;
  573. ox = x, oy = y;
  574. } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
  575. button = 3;
  576. } else {
  577. button -= Button1;
  578. if(button >= 3)
  579. button += 64 - 3;
  580. if(e->xbutton.type == ButtonPress) {
  581. ob = button;
  582. ox = x, oy = y;
  583. }
  584. }
  585. buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
  586. + (state & Mod4Mask ? 8 : 0)
  587. + (state & ControlMask ? 16 : 0);
  588. ttywrite(buf, sizeof(buf));
  589. }
  590. void
  591. bpress(XEvent *e) {
  592. if(IS_SET(MODE_MOUSE)) {
  593. mousereport(e);
  594. } else if(e->xbutton.button == Button1) {
  595. if(sel.bx != -1) {
  596. sel.bx = -1;
  597. tsetdirt(sel.b.y, sel.e.y);
  598. draw();
  599. }
  600. sel.mode = 1;
  601. sel.ex = sel.bx = x2col(e->xbutton.x);
  602. sel.ey = sel.by = y2row(e->xbutton.y);
  603. } else if(e->xbutton.button == Button4) {
  604. ttywrite("\031", 1);
  605. } else if(e->xbutton.button == Button5) {
  606. ttywrite("\005", 1);
  607. }
  608. }
  609. void
  610. selcopy(void) {
  611. char *str, *ptr, *p;
  612. int x, y, bufsize, is_selected = 0, size;
  613. Glyph *gp, *last;
  614. if(sel.bx == -1) {
  615. str = NULL;
  616. } else {
  617. bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
  618. ptr = str = xmalloc(bufsize);
  619. /* append every set & selected glyph to the selection */
  620. for(y = 0; y < term.row; y++) {
  621. gp = &term.line[y][0];
  622. last = gp + term.col;
  623. while(--last >= gp && !(last->state & GLYPH_SET))
  624. /* nothing */;
  625. for(x = 0; gp <= last; x++, ++gp) {
  626. if(!(is_selected = selected(x, y)))
  627. continue;
  628. p = (gp->state & GLYPH_SET) ? gp->c : " ";
  629. size = utf8size(p);
  630. memcpy(ptr, p, size);
  631. ptr += size;
  632. }
  633. /* \n at the end of every selected line except for the last one */
  634. if(is_selected && y < sel.e.y)
  635. *ptr++ = '\n';
  636. }
  637. *ptr = 0;
  638. }
  639. sel.alt = IS_SET(MODE_ALTSCREEN);
  640. xsetsel(str);
  641. }
  642. void
  643. selnotify(XEvent *e) {
  644. ulong nitems, ofs, rem;
  645. int format;
  646. uchar *data;
  647. Atom type;
  648. ofs = 0;
  649. do {
  650. if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
  651. False, AnyPropertyType, &type, &format,
  652. &nitems, &rem, &data)) {
  653. fprintf(stderr, "Clipboard allocation failed\n");
  654. return;
  655. }
  656. ttywrite((const char *) data, nitems * format / 8);
  657. XFree(data);
  658. /* number of 32-bit chunks returned */
  659. ofs += nitems * format / 32;
  660. } while(rem > 0);
  661. }
  662. void
  663. selpaste(const Arg *dummy) {
  664. XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
  665. xw.win, CurrentTime);
  666. }
  667. void selclear(XEvent *e) {
  668. if(sel.bx == -1)
  669. return;
  670. sel.bx = -1;
  671. tsetdirt(sel.b.y, sel.e.y);
  672. }
  673. void
  674. selrequest(XEvent *e) {
  675. XSelectionRequestEvent *xsre;
  676. XSelectionEvent xev;
  677. Atom xa_targets, string;
  678. xsre = (XSelectionRequestEvent *) e;
  679. xev.type = SelectionNotify;
  680. xev.requestor = xsre->requestor;
  681. xev.selection = xsre->selection;
  682. xev.target = xsre->target;
  683. xev.time = xsre->time;
  684. /* reject */
  685. xev.property = None;
  686. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  687. if(xsre->target == xa_targets) {
  688. /* respond with the supported type */
  689. string = sel.xtarget;
  690. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  691. XA_ATOM, 32, PropModeReplace,
  692. (uchar *) &string, 1);
  693. xev.property = xsre->property;
  694. } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
  695. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  696. xsre->target, 8, PropModeReplace,
  697. (uchar *) sel.clip, strlen(sel.clip));
  698. xev.property = xsre->property;
  699. }
  700. /* all done, send a notification to the listener */
  701. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  702. fprintf(stderr, "Error sending SelectionNotify event\n");
  703. }
  704. void
  705. xsetsel(char *str) {
  706. /* register the selection for both the clipboard and the primary */
  707. Atom clipboard;
  708. free(sel.clip);
  709. sel.clip = str;
  710. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
  711. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  712. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  713. }
  714. void
  715. brelease(XEvent *e) {
  716. struct timeval now;
  717. if(IS_SET(MODE_MOUSE)) {
  718. mousereport(e);
  719. return;
  720. }
  721. if(e->xbutton.button == Button2) {
  722. selpaste(NULL);
  723. } else if(e->xbutton.button == Button1) {
  724. sel.mode = 0;
  725. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  726. term.dirty[sel.ey] = 1;
  727. if(sel.bx == sel.ex && sel.by == sel.ey) {
  728. sel.bx = -1;
  729. gettimeofday(&now, NULL);
  730. if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
  731. /* triple click on the line */
  732. sel.b.x = sel.bx = 0;
  733. sel.e.x = sel.ex = term.col;
  734. sel.b.y = sel.e.y = sel.ey;
  735. selcopy();
  736. } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
  737. /* double click to select word */
  738. sel.bx = sel.ex;
  739. while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
  740. term.line[sel.ey][sel.bx-1].c[0] != ' ') {
  741. sel.bx--;
  742. }
  743. sel.b.x = sel.bx;
  744. while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
  745. term.line[sel.ey][sel.ex+1].c[0] != ' ') {
  746. sel.ex++;
  747. }
  748. sel.e.x = sel.ex;
  749. sel.b.y = sel.e.y = sel.ey;
  750. selcopy();
  751. }
  752. } else {
  753. selcopy();
  754. }
  755. }
  756. memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
  757. gettimeofday(&sel.tclick1, NULL);
  758. }
  759. void
  760. bmotion(XEvent *e) {
  761. int starty, endy, oldey, oldex;
  762. if(IS_SET(MODE_MOUSE)) {
  763. mousereport(e);
  764. return;
  765. }
  766. if(sel.mode) {
  767. oldey = sel.ey;
  768. oldex = sel.ex;
  769. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  770. if(oldey != sel.ey || oldex != sel.ex) {
  771. starty = MIN(oldey, sel.ey);
  772. endy = MAX(oldey, sel.ey);
  773. tsetdirt(starty, endy);
  774. }
  775. }
  776. }
  777. void
  778. die(const char *errstr, ...) {
  779. va_list ap;
  780. va_start(ap, errstr);
  781. vfprintf(stderr, errstr, ap);
  782. va_end(ap);
  783. exit(EXIT_FAILURE);
  784. }
  785. void
  786. execsh(void) {
  787. char **args;
  788. char *envshell = getenv("SHELL");
  789. const struct passwd *pass = getpwuid(getuid());
  790. char buf[sizeof(long) * 8 + 1];
  791. unsetenv("COLUMNS");
  792. unsetenv("LINES");
  793. unsetenv("TERMCAP");
  794. if(pass) {
  795. setenv("LOGNAME", pass->pw_name, 1);
  796. setenv("USER", pass->pw_name, 1);
  797. setenv("SHELL", pass->pw_shell, 0);
  798. setenv("HOME", pass->pw_dir, 0);
  799. }
  800. snprintf(buf, sizeof(buf), "%lu", xw.win);
  801. setenv("WINDOWID", buf, 1);
  802. signal(SIGCHLD, SIG_DFL);
  803. signal(SIGHUP, SIG_DFL);
  804. signal(SIGINT, SIG_DFL);
  805. signal(SIGQUIT, SIG_DFL);
  806. signal(SIGTERM, SIG_DFL);
  807. signal(SIGALRM, SIG_DFL);
  808. DEFAULT(envshell, shell);
  809. setenv("TERM", termname, 1);
  810. args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
  811. execvp(args[0], args);
  812. exit(EXIT_FAILURE);
  813. }
  814. void
  815. sigchld(int a) {
  816. int stat = 0;
  817. if(waitpid(pid, &stat, 0) < 0)
  818. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  819. if(WIFEXITED(stat)) {
  820. exit(WEXITSTATUS(stat));
  821. } else {
  822. exit(EXIT_FAILURE);
  823. }
  824. }
  825. void
  826. ttynew(void) {
  827. int m, s;
  828. struct winsize w = {term.row, term.col, 0, 0};
  829. /* seems to work fine on linux, openbsd and freebsd */
  830. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  831. die("openpty failed: %s\n", SERRNO);
  832. switch(pid = fork()) {
  833. case -1:
  834. die("fork failed\n");
  835. break;
  836. case 0:
  837. setsid(); /* create a new process group */
  838. dup2(s, STDIN_FILENO);
  839. dup2(s, STDOUT_FILENO);
  840. dup2(s, STDERR_FILENO);
  841. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  842. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  843. close(s);
  844. close(m);
  845. execsh();
  846. break;
  847. default:
  848. close(s);
  849. cmdfd = m;
  850. signal(SIGCHLD, sigchld);
  851. if(opt_io) {
  852. iofd = (!strcmp(opt_io, "-")) ?
  853. STDOUT_FILENO :
  854. open(opt_io, O_WRONLY | O_CREAT, 0666);
  855. if(iofd < 0) {
  856. fprintf(stderr, "Error opening %s:%s\n",
  857. opt_io, strerror(errno));
  858. }
  859. }
  860. }
  861. }
  862. void
  863. dump(char c) {
  864. static int col;
  865. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  866. if(++col % 10 == 0)
  867. fprintf(stderr, "\n");
  868. }
  869. void
  870. ttyread(void) {
  871. static char buf[BUFSIZ];
  872. static int buflen = 0;
  873. char *ptr;
  874. char s[UTF_SIZ];
  875. int charsize; /* size of utf8 char in bytes */
  876. long utf8c;
  877. int ret;
  878. /* append read bytes to unprocessed bytes */
  879. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  880. die("Couldn't read from shell: %s\n", SERRNO);
  881. /* process every complete utf8 char */
  882. buflen += ret;
  883. ptr = buf;
  884. while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
  885. charsize = utf8decode(ptr, &utf8c);
  886. utf8encode(&utf8c, s);
  887. tputc(s, charsize);
  888. ptr += charsize;
  889. buflen -= charsize;
  890. }
  891. /* keep any uncomplete utf8 char for the next call */
  892. memmove(buf, ptr, buflen);
  893. }
  894. void
  895. ttywrite(const char *s, size_t n) {
  896. if(write(cmdfd, s, n) == -1)
  897. die("write error on tty: %s\n", SERRNO);
  898. }
  899. void
  900. ttyresize(void) {
  901. struct winsize w;
  902. w.ws_row = term.row;
  903. w.ws_col = term.col;
  904. w.ws_xpixel = xw.tw;
  905. w.ws_ypixel = xw.th;
  906. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  907. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  908. }
  909. void
  910. tsetdirt(int top, int bot) {
  911. int i;
  912. LIMIT(top, 0, term.row-1);
  913. LIMIT(bot, 0, term.row-1);
  914. for(i = top; i <= bot; i++)
  915. term.dirty[i] = 1;
  916. }
  917. void
  918. tfulldirt(void) {
  919. tsetdirt(0, term.row-1);
  920. }
  921. void
  922. tcursor(int mode) {
  923. static TCursor c;
  924. if(mode == CURSOR_SAVE) {
  925. c = term.c;
  926. } else if(mode == CURSOR_LOAD) {
  927. term.c = c;
  928. tmoveto(c.x, c.y);
  929. }
  930. }
  931. void
  932. treset(void) {
  933. uint i;
  934. term.c = (TCursor){{
  935. .mode = ATTR_NULL,
  936. .fg = defaultfg,
  937. .bg = defaultbg
  938. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  939. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  940. for(i = tabspaces; i < term.col; i += tabspaces)
  941. term.tabs[i] = 1;
  942. term.top = 0;
  943. term.bot = term.row - 1;
  944. term.mode = MODE_WRAP;
  945. tclearregion(0, 0, term.col-1, term.row-1);
  946. tmoveto(0, 0);
  947. tcursor(CURSOR_SAVE);
  948. }
  949. void
  950. tnew(int col, int row) {
  951. /* set screen size */
  952. term.row = row;
  953. term.col = col;
  954. term.line = xmalloc(term.row * sizeof(Line));
  955. term.alt = xmalloc(term.row * sizeof(Line));
  956. term.dirty = xmalloc(term.row * sizeof(*term.dirty));
  957. term.tabs = xmalloc(term.col * sizeof(*term.tabs));
  958. for(row = 0; row < term.row; row++) {
  959. term.line[row] = xmalloc(term.col * sizeof(Glyph));
  960. term.alt [row] = xmalloc(term.col * sizeof(Glyph));
  961. term.dirty[row] = 0;
  962. }
  963. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  964. /* setup screen */
  965. treset();
  966. }
  967. void
  968. tswapscreen(void) {
  969. Line *tmp = term.line;
  970. term.line = term.alt;
  971. term.alt = tmp;
  972. term.mode ^= MODE_ALTSCREEN;
  973. tfulldirt();
  974. }
  975. void
  976. tscrolldown(int orig, int n) {
  977. int i;
  978. Line temp;
  979. LIMIT(n, 0, term.bot-orig+1);
  980. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  981. for(i = term.bot; i >= orig+n; i--) {
  982. temp = term.line[i];
  983. term.line[i] = term.line[i-n];
  984. term.line[i-n] = temp;
  985. term.dirty[i] = 1;
  986. term.dirty[i-n] = 1;
  987. }
  988. selscroll(orig, n);
  989. }
  990. void
  991. tscrollup(int orig, int n) {
  992. int i;
  993. Line temp;
  994. LIMIT(n, 0, term.bot-orig+1);
  995. tclearregion(0, orig, term.col-1, orig+n-1);
  996. for(i = orig; i <= term.bot-n; i++) {
  997. temp = term.line[i];
  998. term.line[i] = term.line[i+n];
  999. term.line[i+n] = temp;
  1000. term.dirty[i] = 1;
  1001. term.dirty[i+n] = 1;
  1002. }
  1003. selscroll(orig, -n);
  1004. }
  1005. void
  1006. selscroll(int orig, int n) {
  1007. if(sel.bx == -1)
  1008. return;
  1009. if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
  1010. if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
  1011. sel.bx = -1;
  1012. return;
  1013. }
  1014. if(sel.by < term.top) {
  1015. sel.by = term.top;
  1016. sel.bx = 0;
  1017. }
  1018. if(sel.ey > term.bot) {
  1019. sel.ey = term.bot;
  1020. sel.ex = term.col;
  1021. }
  1022. sel.b.y = sel.by, sel.b.x = sel.bx;
  1023. sel.e.y = sel.ey, sel.e.x = sel.ex;
  1024. }
  1025. }
  1026. void
  1027. tnewline(int first_col) {
  1028. int y = term.c.y;
  1029. if(y == term.bot) {
  1030. tscrollup(term.top, 1);
  1031. } else {
  1032. y++;
  1033. }
  1034. tmoveto(first_col ? 0 : term.c.x, y);
  1035. }
  1036. void
  1037. csiparse(void) {
  1038. /* int noarg = 1; */
  1039. char *p = csiescseq.buf;
  1040. csiescseq.narg = 0;
  1041. if(*p == '?')
  1042. csiescseq.priv = 1, p++;
  1043. while(p < csiescseq.buf+csiescseq.len) {
  1044. while(isdigit(*p)) {
  1045. csiescseq.arg[csiescseq.narg] *= 10;
  1046. csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
  1047. }
  1048. if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
  1049. csiescseq.narg++, p++;
  1050. } else {
  1051. csiescseq.mode = *p;
  1052. csiescseq.narg++;
  1053. return;
  1054. }
  1055. }
  1056. }
  1057. /* for absolute user moves, when decom is set */
  1058. void
  1059. tmoveato(int x, int y) {
  1060. tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
  1061. }
  1062. void
  1063. tmoveto(int x, int y) {
  1064. int miny, maxy;
  1065. if(term.c.state & CURSOR_ORIGIN) {
  1066. miny = term.top;
  1067. maxy = term.bot;
  1068. } else {
  1069. miny = 0;
  1070. maxy = term.row - 1;
  1071. }
  1072. LIMIT(x, 0, term.col-1);
  1073. LIMIT(y, miny, maxy);
  1074. term.c.state &= ~CURSOR_WRAPNEXT;
  1075. term.c.x = x;
  1076. term.c.y = y;
  1077. }
  1078. void
  1079. tsetchar(char *c, Glyph *attr, int x, int y) {
  1080. static char *vt100_0[62] = { /* 0x41 - 0x7e */
  1081. "", "", "", "", "", "", "", /* A - G */
  1082. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  1083. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  1084. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  1085. "", "", "", "", "", "", "°", "±", /* ` - g */
  1086. "", "", "", "", "", "", "", "", /* h - o */
  1087. "", "", "", "", "", "", "", "", /* p - w */
  1088. "", "", "", "π", "", "£", "·", /* x - ~ */
  1089. };
  1090. /*
  1091. * The table is proudly stolen from rxvt.
  1092. */
  1093. if(attr->mode & ATTR_GFX) {
  1094. if(c[0] >= 0x41 && c[0] <= 0x7e
  1095. && vt100_0[c[0] - 0x41]) {
  1096. c = vt100_0[c[0] - 0x41];
  1097. }
  1098. }
  1099. term.dirty[y] = 1;
  1100. term.line[y][x] = *attr;
  1101. memcpy(term.line[y][x].c, c, UTF_SIZ);
  1102. term.line[y][x].state |= GLYPH_SET;
  1103. }
  1104. void
  1105. tclearregion(int x1, int y1, int x2, int y2) {
  1106. int x, y, temp;
  1107. if(x1 > x2)
  1108. temp = x1, x1 = x2, x2 = temp;
  1109. if(y1 > y2)
  1110. temp = y1, y1 = y2, y2 = temp;
  1111. LIMIT(x1, 0, term.col-1);
  1112. LIMIT(x2, 0, term.col-1);
  1113. LIMIT(y1, 0, term.row-1);
  1114. LIMIT(y2, 0, term.row-1);
  1115. for(y = y1; y <= y2; y++) {
  1116. term.dirty[y] = 1;
  1117. for(x = x1; x <= x2; x++)
  1118. term.line[y][x].state = 0;
  1119. }
  1120. }
  1121. void
  1122. tdeletechar(int n) {
  1123. int src = term.c.x + n;
  1124. int dst = term.c.x;
  1125. int size = term.col - src;
  1126. term.dirty[term.c.y] = 1;
  1127. if(src >= term.col) {
  1128. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1129. return;
  1130. }
  1131. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
  1132. size * sizeof(Glyph));
  1133. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1134. }
  1135. void
  1136. tinsertblank(int n) {
  1137. int src = term.c.x;
  1138. int dst = src + n;
  1139. int size = term.col - dst;
  1140. term.dirty[term.c.y] = 1;
  1141. if(dst >= term.col) {
  1142. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1143. return;
  1144. }
  1145. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
  1146. size * sizeof(Glyph));
  1147. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1148. }
  1149. void
  1150. tinsertblankline(int n) {
  1151. if(term.c.y < term.top || term.c.y > term.bot)
  1152. return;
  1153. tscrolldown(term.c.y, n);
  1154. }
  1155. void
  1156. tdeleteline(int n) {
  1157. if(term.c.y < term.top || term.c.y > term.bot)
  1158. return;
  1159. tscrollup(term.c.y, n);
  1160. }
  1161. void
  1162. tsetattr(int *attr, int l) {
  1163. int i;
  1164. for(i = 0; i < l; i++) {
  1165. switch(attr[i]) {
  1166. case 0:
  1167. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
  1168. | ATTR_ITALIC | ATTR_BLINK);
  1169. term.c.attr.fg = defaultfg;
  1170. term.c.attr.bg = defaultbg;
  1171. break;
  1172. case 1:
  1173. term.c.attr.mode |= ATTR_BOLD;
  1174. break;
  1175. case 3: /* enter standout (highlight) */
  1176. term.c.attr.mode |= ATTR_ITALIC;
  1177. break;
  1178. case 4:
  1179. term.c.attr.mode |= ATTR_UNDERLINE;
  1180. break;
  1181. case 5:
  1182. term.c.attr.mode |= ATTR_BLINK;
  1183. break;
  1184. case 7:
  1185. term.c.attr.mode |= ATTR_REVERSE;
  1186. break;
  1187. case 21:
  1188. case 22:
  1189. term.c.attr.mode &= ~ATTR_BOLD;
  1190. break;
  1191. case 23: /* leave standout (highlight) mode */
  1192. term.c.attr.mode &= ~ATTR_ITALIC;
  1193. break;
  1194. case 24:
  1195. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1196. break;
  1197. case 25:
  1198. term.c.attr.mode &= ~ATTR_BLINK;
  1199. break;
  1200. case 27:
  1201. term.c.attr.mode &= ~ATTR_REVERSE;
  1202. break;
  1203. case 38:
  1204. if(i + 2 < l && attr[i + 1] == 5) {
  1205. i += 2;
  1206. if(BETWEEN(attr[i], 0, 255)) {
  1207. term.c.attr.fg = attr[i];
  1208. } else {
  1209. fprintf(stderr,
  1210. "erresc: bad fgcolor %d\n",
  1211. attr[i]);
  1212. }
  1213. } else {
  1214. fprintf(stderr,
  1215. "erresc(38): gfx attr %d unknown\n",
  1216. attr[i]);
  1217. }
  1218. break;
  1219. case 39:
  1220. term.c.attr.fg = defaultfg;
  1221. break;
  1222. case 48:
  1223. if(i + 2 < l && attr[i + 1] == 5) {
  1224. i += 2;
  1225. if(BETWEEN(attr[i], 0, 255)) {
  1226. term.c.attr.bg = attr[i];
  1227. } else {
  1228. fprintf(stderr,
  1229. "erresc: bad bgcolor %d\n",
  1230. attr[i]);
  1231. }
  1232. } else {
  1233. fprintf(stderr,
  1234. "erresc(48): gfx attr %d unknown\n",
  1235. attr[i]);
  1236. }
  1237. break;
  1238. case 49:
  1239. term.c.attr.bg = defaultbg;
  1240. break;
  1241. default:
  1242. if(BETWEEN(attr[i], 30, 37)) {
  1243. term.c.attr.fg = attr[i] - 30;
  1244. } else if(BETWEEN(attr[i], 40, 47)) {
  1245. term.c.attr.bg = attr[i] - 40;
  1246. } else if(BETWEEN(attr[i], 90, 97)) {
  1247. term.c.attr.fg = attr[i] - 90 + 8;
  1248. } else if(BETWEEN(attr[i], 100, 107)) {
  1249. term.c.attr.bg = attr[i] - 100 + 8;
  1250. } else {
  1251. fprintf(stderr,
  1252. "erresc(default): gfx attr %d unknown\n",
  1253. attr[i]), csidump();
  1254. }
  1255. break;
  1256. }
  1257. }
  1258. }
  1259. void
  1260. tsetscroll(int t, int b) {
  1261. int temp;
  1262. LIMIT(t, 0, term.row-1);
  1263. LIMIT(b, 0, term.row-1);
  1264. if(t > b) {
  1265. temp = t;
  1266. t = b;
  1267. b = temp;
  1268. }
  1269. term.top = t;
  1270. term.bot = b;
  1271. }
  1272. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1273. void
  1274. tsetmode(bool priv, bool set, int *args, int narg) {
  1275. int *lim, mode;
  1276. bool alt;
  1277. for(lim = args + narg; args < lim; ++args) {
  1278. if(priv) {
  1279. switch(*args) {
  1280. break;
  1281. case 1: /* DECCKM -- Cursor key */
  1282. MODBIT(term.mode, set, MODE_APPCURSOR);
  1283. break;
  1284. case 5: /* DECSCNM -- Reverse video */
  1285. mode = term.mode;
  1286. MODBIT(term.mode, set, MODE_REVERSE);
  1287. if(mode != term.mode)
  1288. redraw();
  1289. break;
  1290. case 6: /* DECOM -- Origin */
  1291. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1292. tmoveato(0, 0);
  1293. break;
  1294. case 7: /* DECAWM -- Auto wrap */
  1295. MODBIT(term.mode, set, MODE_WRAP);
  1296. break;
  1297. case 0: /* Error (IGNORED) */
  1298. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1299. case 3: /* DECCOLM -- Column (IGNORED) */
  1300. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1301. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1302. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1303. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1304. case 42: /* DECNRCM -- National characters (IGNORED) */
  1305. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1306. break;
  1307. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1308. MODBIT(term.mode, !set, MODE_HIDE);
  1309. break;
  1310. case 1000: /* 1000,1002: enable xterm mouse report */
  1311. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1312. break;
  1313. case 1002:
  1314. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1315. break;
  1316. case 1049: /* = 1047 and 1048 */
  1317. case 47:
  1318. case 1047: {
  1319. alt = IS_SET(MODE_ALTSCREEN) != 0;
  1320. if(alt)
  1321. tclearregion(0, 0, term.col-1, term.row-1);
  1322. if(set ^ alt) /* set is always 1 or 0 */
  1323. tswapscreen();
  1324. if(*args != 1049)
  1325. break;
  1326. }
  1327. /* pass through */
  1328. case 1048:
  1329. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1330. break;
  1331. default:
  1332. fprintf(stderr,
  1333. "erresc: unknown private set/reset mode %d\n",
  1334. *args);
  1335. break;
  1336. }
  1337. } else {
  1338. switch(*args) {
  1339. case 0: /* Error (IGNORED) */
  1340. break;
  1341. case 2: /* KAM -- keyboard action */
  1342. MODBIT(term.mode, set, MODE_KBDLOCK);
  1343. break;
  1344. case 4: /* IRM -- Insertion-replacement */
  1345. MODBIT(term.mode, set, MODE_INSERT);
  1346. break;
  1347. case 12: /* SRM -- Send/Receive */
  1348. MODBIT(term.mode, !set, MODE_ECHO);
  1349. break;
  1350. case 20: /* LNM -- Linefeed/new line */
  1351. MODBIT(term.mode, set, MODE_CRLF);
  1352. break;
  1353. default:
  1354. fprintf(stderr,
  1355. "erresc: unknown set/reset mode %d\n",
  1356. *args);
  1357. break;
  1358. }
  1359. }
  1360. }
  1361. }
  1362. #undef MODBIT
  1363. void
  1364. csihandle(void) {
  1365. switch(csiescseq.mode) {
  1366. default:
  1367. unknown:
  1368. fprintf(stderr, "erresc: unknown csi ");
  1369. csidump();
  1370. /* die(""); */
  1371. break;
  1372. case '@': /* ICH -- Insert <n> blank char */
  1373. DEFAULT(csiescseq.arg[0], 1);
  1374. tinsertblank(csiescseq.arg[0]);
  1375. break;
  1376. case 'A': /* CUU -- Cursor <n> Up */
  1377. DEFAULT(csiescseq.arg[0], 1);
  1378. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1379. break;
  1380. case 'B': /* CUD -- Cursor <n> Down */
  1381. case 'e': /* VPR --Cursor <n> Down */
  1382. DEFAULT(csiescseq.arg[0], 1);
  1383. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1384. break;
  1385. case 'c': /* DA -- Device Attributes */
  1386. if(csiescseq.arg[0] == 0)
  1387. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1388. break;
  1389. case 'C': /* CUF -- Cursor <n> Forward */
  1390. case 'a': /* HPR -- Cursor <n> Forward */
  1391. DEFAULT(csiescseq.arg[0], 1);
  1392. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1393. break;
  1394. case 'D': /* CUB -- Cursor <n> Backward */
  1395. DEFAULT(csiescseq.arg[0], 1);
  1396. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1397. break;
  1398. case 'E': /* CNL -- Cursor <n> Down and first col */
  1399. DEFAULT(csiescseq.arg[0], 1);
  1400. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1401. break;
  1402. case 'F': /* CPL -- Cursor <n> Up and first col */
  1403. DEFAULT(csiescseq.arg[0], 1);
  1404. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1405. break;
  1406. case 'g': /* TBC -- Tabulation clear */
  1407. switch (csiescseq.arg[0]) {
  1408. case 0: /* clear current tab stop */
  1409. term.tabs[term.c.x] = 0;
  1410. break;
  1411. case 3: /* clear all the tabs */
  1412. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1413. break;
  1414. default:
  1415. goto unknown;
  1416. }
  1417. break;
  1418. case 'G': /* CHA -- Move to <col> */
  1419. case '`': /* HPA */
  1420. DEFAULT(csiescseq.arg[0], 1);
  1421. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1422. break;
  1423. case 'H': /* CUP -- Move to <row> <col> */
  1424. case 'f': /* HVP */
  1425. DEFAULT(csiescseq.arg[0], 1);
  1426. DEFAULT(csiescseq.arg[1], 1);
  1427. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1428. break;
  1429. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1430. DEFAULT(csiescseq.arg[0], 1);
  1431. while(csiescseq.arg[0]--)
  1432. tputtab(1);
  1433. break;
  1434. case 'J': /* ED -- Clear screen */
  1435. sel.bx = -1;
  1436. switch(csiescseq.arg[0]) {
  1437. case 0: /* below */
  1438. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1439. if(term.c.y < term.row-1)
  1440. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  1441. break;
  1442. case 1: /* above */
  1443. if(term.c.y > 1)
  1444. tclearregion(0, 0, term.col-1, term.c.y-1);
  1445. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1446. break;
  1447. case 2: /* all */
  1448. tclearregion(0, 0, term.col-1, term.row-1);
  1449. break;
  1450. default:
  1451. goto unknown;
  1452. }
  1453. break;
  1454. case 'K': /* EL -- Clear line */
  1455. switch(csiescseq.arg[0]) {
  1456. case 0: /* right */
  1457. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1458. break;
  1459. case 1: /* left */
  1460. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1461. break;
  1462. case 2: /* all */
  1463. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1464. break;
  1465. }
  1466. break;
  1467. case 'S': /* SU -- Scroll <n> line up */
  1468. DEFAULT(csiescseq.arg[0], 1);
  1469. tscrollup(term.top, csiescseq.arg[0]);
  1470. break;
  1471. case 'T': /* SD -- Scroll <n> line down */
  1472. DEFAULT(csiescseq.arg[0], 1);
  1473. tscrolldown(term.top, csiescseq.arg[0]);
  1474. break;
  1475. case 'L': /* IL -- Insert <n> blank lines */
  1476. DEFAULT(csiescseq.arg[0], 1);
  1477. tinsertblankline(csiescseq.arg[0]);
  1478. break;
  1479. case 'l': /* RM -- Reset Mode */
  1480. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1481. break;
  1482. case 'M': /* DL -- Delete <n> lines */
  1483. DEFAULT(csiescseq.arg[0], 1);
  1484. tdeleteline(csiescseq.arg[0]);
  1485. break;
  1486. case 'X': /* ECH -- Erase <n> char */
  1487. DEFAULT(csiescseq.arg[0], 1);
  1488. tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
  1489. break;
  1490. case 'P': /* DCH -- Delete <n> char */
  1491. DEFAULT(csiescseq.arg[0], 1);
  1492. tdeletechar(csiescseq.arg[0]);
  1493. break;
  1494. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1495. DEFAULT(csiescseq.arg[0], 1);
  1496. while(csiescseq.arg[0]--)
  1497. tputtab(0);
  1498. break;
  1499. case 'd': /* VPA -- Move to <row> */
  1500. DEFAULT(csiescseq.arg[0], 1);
  1501. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1502. break;
  1503. case 'h': /* SM -- Set terminal mode */
  1504. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1505. break;
  1506. case 'm': /* SGR -- Terminal attribute (color) */
  1507. tsetattr(csiescseq.arg, csiescseq.narg);
  1508. break;
  1509. case 'r': /* DECSTBM -- Set Scrolling Region */
  1510. if(csiescseq.priv) {
  1511. goto unknown;
  1512. } else {
  1513. DEFAULT(csiescseq.arg[0], 1);
  1514. DEFAULT(csiescseq.arg[1], term.row);
  1515. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1516. tmoveato(0, 0);
  1517. }
  1518. break;
  1519. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1520. tcursor(CURSOR_SAVE);
  1521. break;
  1522. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1523. tcursor(CURSOR_LOAD);
  1524. break;
  1525. }
  1526. }
  1527. void
  1528. csidump(void) {
  1529. int i;
  1530. uint c;
  1531. printf("ESC[");
  1532. for(i = 0; i < csiescseq.len; i++) {
  1533. c = csiescseq.buf[i] & 0xff;
  1534. if(isprint(c)) {
  1535. putchar(c);
  1536. } else if(c == '\n') {
  1537. printf("(\\n)");
  1538. } else if(c == '\r') {
  1539. printf("(\\r)");
  1540. } else if(c == 0x1b) {
  1541. printf("(\\e)");
  1542. } else {
  1543. printf("(%02x)", c);
  1544. }
  1545. }
  1546. putchar('\n');
  1547. }
  1548. void
  1549. csireset(void) {
  1550. memset(&csiescseq, 0, sizeof(csiescseq));
  1551. }
  1552. void
  1553. strhandle(void) {
  1554. char *p;
  1555. /*
  1556. * TODO: make this being useful in case of color palette change.
  1557. */
  1558. strparse();
  1559. p = strescseq.buf;
  1560. switch(strescseq.type) {
  1561. case ']': /* OSC -- Operating System Command */
  1562. switch(p[0]) {
  1563. case '0':
  1564. case '1':
  1565. case '2':
  1566. /*
  1567. * TODO: Handle special chars in string, like umlauts.
  1568. */
  1569. if(p[1] == ';') {
  1570. XStoreName(xw.dpy, xw.win, strescseq.buf+2);
  1571. }
  1572. break;
  1573. case ';':
  1574. XStoreName(xw.dpy, xw.win, strescseq.buf+1);
  1575. break;
  1576. case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
  1577. break;
  1578. default:
  1579. fprintf(stderr, "erresc: unknown str ");
  1580. strdump();
  1581. break;
  1582. }
  1583. break;
  1584. case 'k': /* old title set compatibility */
  1585. XStoreName(xw.dpy, xw.win, strescseq.buf);
  1586. break;
  1587. case 'P': /* DSC -- Device Control String */
  1588. case '_': /* APC -- Application Program Command */
  1589. case '^': /* PM -- Privacy Message */
  1590. default:
  1591. fprintf(stderr, "erresc: unknown str ");
  1592. strdump();
  1593. /* die(""); */
  1594. break;
  1595. }
  1596. }
  1597. void
  1598. strparse(void) {
  1599. /*
  1600. * TODO: Implement parsing like for CSI when required.
  1601. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1602. */
  1603. return;
  1604. }
  1605. void
  1606. strdump(void) {
  1607. int i;
  1608. uint c;
  1609. printf("ESC%c", strescseq.type);
  1610. for(i = 0; i < strescseq.len; i++) {
  1611. c = strescseq.buf[i] & 0xff;
  1612. if(isprint(c)) {
  1613. putchar(c);
  1614. } else if(c == '\n') {
  1615. printf("(\\n)");
  1616. } else if(c == '\r') {
  1617. printf("(\\r)");
  1618. } else if(c == 0x1b) {
  1619. printf("(\\e)");
  1620. } else {
  1621. printf("(%02x)", c);
  1622. }
  1623. }
  1624. printf("ESC\\\n");
  1625. }
  1626. void
  1627. strreset(void) {
  1628. memset(&strescseq, 0, sizeof(strescseq));
  1629. }
  1630. void
  1631. tputtab(bool forward) {
  1632. uint x = term.c.x;
  1633. if(forward) {
  1634. if(x == term.col)
  1635. return;
  1636. for(++x; x < term.col && !term.tabs[x]; ++x)
  1637. /* nothing */ ;
  1638. } else {
  1639. if(x == 0)
  1640. return;
  1641. for(--x; x > 0 && !term.tabs[x]; --x)
  1642. /* nothing */ ;
  1643. }
  1644. tmoveto(x, term.c.y);
  1645. }
  1646. void
  1647. techo(char *buf, int len) {
  1648. for(; len > 0; buf++, len--) {
  1649. char c = *buf;
  1650. if(c == '\033') { /* escape */
  1651. tputc("^", 1);
  1652. tputc("[", 1);
  1653. } else if (c < '\x20') { /* control code */
  1654. if(c != '\n' && c != '\r' && c != '\t') {
  1655. c |= '\x40';
  1656. tputc("^", 1);
  1657. }
  1658. tputc(&c, 1);
  1659. } else {
  1660. break;
  1661. }
  1662. }
  1663. if (len)
  1664. tputc(buf, len);
  1665. }
  1666. void
  1667. tputc(char *c, int len) {
  1668. uchar ascii = *c;
  1669. bool control = ascii < '\x20' || ascii == 0177;
  1670. if(iofd != -1) {
  1671. if (xwrite(iofd, c, len) < 0) {
  1672. fprintf(stderr, "Error writting in %s:%s\n",
  1673. opt_io, strerror(errno));
  1674. close(iofd);
  1675. iofd = -1;
  1676. }
  1677. }
  1678. /*
  1679. * STR sequences must be checked before anything else
  1680. * because it can use some control codes as part of the sequence.
  1681. */
  1682. if(term.esc & ESC_STR) {
  1683. switch(ascii) {
  1684. case '\033':
  1685. term.esc = ESC_START | ESC_STR_END;
  1686. break;
  1687. case '\a': /* backwards compatibility to xterm */
  1688. term.esc = 0;
  1689. strhandle();
  1690. break;
  1691. default:
  1692. strescseq.buf[strescseq.len++] = ascii;
  1693. if(strescseq.len+1 >= STR_BUF_SIZ) {
  1694. term.esc = 0;
  1695. strhandle();
  1696. }
  1697. }
  1698. return;
  1699. }
  1700. /*
  1701. * Actions of control codes must be performed as soon they arrive
  1702. * because they can be embedded inside a control sequence, and
  1703. * they must not cause conflicts with sequences.
  1704. */
  1705. if(control) {
  1706. switch(ascii) {
  1707. case '\t': /* HT */
  1708. tputtab(1);
  1709. return;
  1710. case '\b': /* BS */
  1711. tmoveto(term.c.x-1, term.c.y);
  1712. return;
  1713. case '\r': /* CR */
  1714. tmoveto(0, term.c.y);
  1715. return;
  1716. case '\f': /* LF */
  1717. case '\v': /* VT */
  1718. case '\n': /* LF */
  1719. /* go to first col if the mode is set */
  1720. tnewline(IS_SET(MODE_CRLF));
  1721. return;
  1722. case '\a': /* BEL */
  1723. if(!(xw.state & WIN_FOCUSED))
  1724. xseturgency(1);
  1725. return;
  1726. case '\033': /* ESC */
  1727. csireset();
  1728. term.esc = ESC_START;
  1729. return;
  1730. case '\016': /* SO */
  1731. term.c.attr.mode |= ATTR_GFX;
  1732. return;
  1733. case '\017': /* SI */
  1734. term.c.attr.mode &= ~ATTR_GFX;
  1735. return;
  1736. case '\032': /* SUB */
  1737. case '\030': /* CAN */
  1738. csireset();
  1739. return;
  1740. case '\005': /* ENQ (IGNORED) */
  1741. case '\000': /* NUL (IGNORED) */
  1742. case '\021': /* XON (IGNORED) */
  1743. case '\023': /* XOFF (IGNORED) */
  1744. case 0177: /* DEL (IGNORED) */
  1745. return;
  1746. }
  1747. } else if(term.esc & ESC_START) {
  1748. if(term.esc & ESC_CSI) {
  1749. csiescseq.buf[csiescseq.len++] = ascii;
  1750. if(BETWEEN(ascii, 0x40, 0x7E)
  1751. || csiescseq.len >= ESC_BUF_SIZ) {
  1752. term.esc = 0;
  1753. csiparse(), csihandle();
  1754. }
  1755. } else if(term.esc & ESC_STR_END) {
  1756. term.esc = 0;
  1757. if(ascii == '\\')
  1758. strhandle();
  1759. } else if(term.esc & ESC_ALTCHARSET) {
  1760. switch(ascii) {
  1761. case '0': /* Line drawing set */
  1762. term.c.attr.mode |= ATTR_GFX;
  1763. break;
  1764. case 'B': /* USASCII */
  1765. term.c.attr.mode &= ~ATTR_GFX;
  1766. break;
  1767. case 'A': /* UK (IGNORED) */
  1768. case '<': /* multinational charset (IGNORED) */
  1769. case '5': /* Finnish (IGNORED) */
  1770. case 'C': /* Finnish (IGNORED) */
  1771. case 'K': /* German (IGNORED) */
  1772. break;
  1773. default:
  1774. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1775. }
  1776. term.esc = 0;
  1777. } else if(term.esc & ESC_TEST) {
  1778. if(ascii == '8') { /* DEC screen alignment test. */
  1779. char E[UTF_SIZ] = "E";
  1780. int x, y;
  1781. for(x = 0; x < term.col; ++x) {
  1782. for(y = 0; y < term.row; ++y)
  1783. tsetchar(E, &term.c.attr, x, y);
  1784. }
  1785. }
  1786. term.esc = 0;
  1787. } else {
  1788. switch(ascii) {
  1789. case '[':
  1790. term.esc |= ESC_CSI;
  1791. break;
  1792. case '#':
  1793. term.esc |= ESC_TEST;
  1794. break;
  1795. case 'P': /* DCS -- Device Control String */
  1796. case '_': /* APC -- Application Program Command */
  1797. case '^': /* PM -- Privacy Message */
  1798. case ']': /* OSC -- Operating System Command */
  1799. case 'k': /* old title set compatibility */
  1800. strreset();
  1801. strescseq.type = ascii;
  1802. term.esc |= ESC_STR;
  1803. break;
  1804. case '(': /* set primary charset G0 */
  1805. term.esc |= ESC_ALTCHARSET;
  1806. break;
  1807. case ')': /* set secondary charset G1 (IGNORED) */
  1808. case '*': /* set tertiary charset G2 (IGNORED) */
  1809. case '+': /* set quaternary charset G3 (IGNORED) */
  1810. term.esc = 0;
  1811. break;
  1812. case 'D': /* IND -- Linefeed */
  1813. if(term.c.y == term.bot) {
  1814. tscrollup(term.top, 1);
  1815. } else {
  1816. tmoveto(term.c.x, term.c.y+1);
  1817. }
  1818. term.esc = 0;
  1819. break;
  1820. case 'E': /* NEL -- Next line */
  1821. tnewline(1); /* always go to first col */
  1822. term.esc = 0;
  1823. break;
  1824. case 'H': /* HTS -- Horizontal tab stop */
  1825. term.tabs[term.c.x] = 1;
  1826. term.esc = 0;
  1827. break;
  1828. case 'M': /* RI -- Reverse index */
  1829. if(term.c.y == term.top) {
  1830. tscrolldown(term.top, 1);
  1831. } else {
  1832. tmoveto(term.c.x, term.c.y-1);
  1833. }
  1834. term.esc = 0;
  1835. break;
  1836. case 'Z': /* DECID -- Identify Terminal */
  1837. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1838. term.esc = 0;
  1839. break;
  1840. case 'c': /* RIS -- Reset to inital state */
  1841. treset();
  1842. term.esc = 0;
  1843. xresettitle();
  1844. break;
  1845. case '=': /* DECPAM -- Application keypad */
  1846. term.mode |= MODE_APPKEYPAD;
  1847. term.esc = 0;
  1848. break;
  1849. case '>': /* DECPNM -- Normal keypad */
  1850. term.mode &= ~MODE_APPKEYPAD;
  1851. term.esc = 0;
  1852. break;
  1853. case '7': /* DECSC -- Save Cursor */
  1854. tcursor(CURSOR_SAVE);
  1855. term.esc = 0;
  1856. break;
  1857. case '8': /* DECRC -- Restore Cursor */
  1858. tcursor(CURSOR_LOAD);
  1859. term.esc = 0;
  1860. break;
  1861. case '\\': /* ST -- Stop */
  1862. term.esc = 0;
  1863. break;
  1864. default:
  1865. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1866. (uchar) ascii, isprint(ascii)? ascii:'.');
  1867. term.esc = 0;
  1868. }
  1869. }
  1870. /*
  1871. * All characters which forms part of a sequence are not
  1872. * printed
  1873. */
  1874. return;
  1875. }
  1876. /*
  1877. * Display control codes only if we are in graphic mode
  1878. */
  1879. if(control && !(term.c.attr.mode & ATTR_GFX))
  1880. return;
  1881. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1882. sel.bx = -1;
  1883. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1884. tnewline(1); /* always go to first col */
  1885. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  1886. if(term.c.x+1 < term.col)
  1887. tmoveto(term.c.x+1, term.c.y);
  1888. else
  1889. term.c.state |= CURSOR_WRAPNEXT;
  1890. }
  1891. int
  1892. tresize(int col, int row) {
  1893. int i, x;
  1894. int minrow = MIN(row, term.row);
  1895. int mincol = MIN(col, term.col);
  1896. int slide = term.c.y - row + 1;
  1897. bool *bp;
  1898. if(col < 1 || row < 1)
  1899. return 0;
  1900. /* free unneeded rows */
  1901. i = 0;
  1902. if(slide > 0) {
  1903. /* slide screen to keep cursor where we expect it -
  1904. * tscrollup would work here, but we can optimize to
  1905. * memmove because we're freeing the earlier lines */
  1906. for(/* i = 0 */; i < slide; i++) {
  1907. free(term.line[i]);
  1908. free(term.alt[i]);
  1909. }
  1910. memmove(term.line, term.line + slide, row * sizeof(Line));
  1911. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1912. }
  1913. for(i += row; i < term.row; i++) {
  1914. free(term.line[i]);
  1915. free(term.alt[i]);
  1916. }
  1917. /* resize to new height */
  1918. term.line = xrealloc(term.line, row * sizeof(Line));
  1919. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1920. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1921. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1922. /* resize each row to new width, zero-pad if needed */
  1923. for(i = 0; i < minrow; i++) {
  1924. term.dirty[i] = 1;
  1925. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1926. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1927. for(x = mincol; x < col; x++) {
  1928. term.line[i][x].state = 0;
  1929. term.alt[i][x].state = 0;
  1930. }
  1931. }
  1932. /* allocate any new rows */
  1933. for(/* i == minrow */; i < row; i++) {
  1934. term.dirty[i] = 1;
  1935. term.line[i] = xcalloc(col, sizeof(Glyph));
  1936. term.alt [i] = xcalloc(col, sizeof(Glyph));
  1937. }
  1938. if(col > term.col) {
  1939. bp = term.tabs + term.col;
  1940. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1941. while(--bp > term.tabs && !*bp)
  1942. /* nothing */ ;
  1943. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  1944. *bp = 1;
  1945. }
  1946. /* update terminal size */
  1947. term.col = col;
  1948. term.row = row;
  1949. /* reset scrolling region */
  1950. tsetscroll(0, row-1);
  1951. /* make use of the LIMIT in tmoveto */
  1952. tmoveto(term.c.x, term.c.y);
  1953. return (slide > 0);
  1954. }
  1955. void
  1956. xresize(int col, int row) {
  1957. xw.tw = MAX(1, 2*borderpx + col * xw.cw);
  1958. xw.th = MAX(1, 2*borderpx + row * xw.ch);
  1959. XftDrawChange(xw.draw, xw.buf);
  1960. }
  1961. void
  1962. xloadcols(void) {
  1963. int i, r, g, b;
  1964. XRenderColor color = { .alpha = 0 };
  1965. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1966. for(i = 0; i < LEN(colorname); i++) {
  1967. if(!colorname[i])
  1968. continue;
  1969. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
  1970. die("Could not allocate color '%s'\n", colorname[i]);
  1971. }
  1972. }
  1973. /* load colors [16-255] ; same colors as xterm */
  1974. for(i = 16, r = 0; r < 6; r++) {
  1975. for(g = 0; g < 6; g++) {
  1976. for(b = 0; b < 6; b++) {
  1977. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1978. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1979. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1980. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
  1981. die("Could not allocate color %d\n", i);
  1982. }
  1983. i++;
  1984. }
  1985. }
  1986. }
  1987. for(r = 0; r < 24; r++, i++) {
  1988. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1989. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
  1990. &dc.col[i])) {
  1991. die("Could not allocate color %d\n", i);
  1992. }
  1993. }
  1994. }
  1995. void
  1996. xtermclear(int col1, int row1, int col2, int row2) {
  1997. XftDrawRect(xw.draw,
  1998. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  1999. borderpx + col1 * xw.cw,
  2000. borderpx + row1 * xw.ch,
  2001. (col2-col1+1) * xw.cw,
  2002. (row2-row1+1) * xw.ch);
  2003. }
  2004. /*
  2005. * Absolute coordinates.
  2006. */
  2007. void
  2008. xclear(int x1, int y1, int x2, int y2) {
  2009. XftDrawRect(xw.draw,
  2010. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2011. x1, y1, x2-x1, y2-y1);
  2012. }
  2013. void
  2014. xhints(void) {
  2015. XClassHint class = {opt_class ? opt_class : termname, termname};
  2016. XWMHints wm = {.flags = InputHint, .input = 1};
  2017. XSizeHints *sizeh = NULL;
  2018. sizeh = XAllocSizeHints();
  2019. if(xw.isfixed == False) {
  2020. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2021. sizeh->height = xw.h;
  2022. sizeh->width = xw.w;
  2023. sizeh->height_inc = xw.ch;
  2024. sizeh->width_inc = xw.cw;
  2025. sizeh->base_height = 2*borderpx;
  2026. sizeh->base_width = 2*borderpx;
  2027. } else {
  2028. sizeh->flags = PMaxSize | PMinSize;
  2029. sizeh->min_width = sizeh->max_width = xw.fw;
  2030. sizeh->min_height = sizeh->max_height = xw.fh;
  2031. }
  2032. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  2033. XFree(sizeh);
  2034. }
  2035. int
  2036. xloadfont(Font *f, FcPattern *pattern) {
  2037. FcPattern *match;
  2038. FcResult result;
  2039. match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
  2040. if(!match)
  2041. return 1;
  2042. if(!(f->set = XftFontOpenPattern(xw.dpy, match))) {
  2043. FcPatternDestroy(match);
  2044. return 1;
  2045. }
  2046. f->ascent = f->set->ascent;
  2047. f->descent = f->set->descent;
  2048. f->lbearing = 0;
  2049. f->rbearing = f->set->max_advance_width;
  2050. f->height = f->set->height;
  2051. f->width = f->lbearing + f->rbearing;
  2052. return 0;
  2053. }
  2054. void
  2055. xloadfonts(char *fontstr, int fontsize) {
  2056. FcPattern *pattern;
  2057. FcResult result;
  2058. double fontval;
  2059. if(fontstr[0] == '-') {
  2060. pattern = XftXlfdParse(fontstr, False, False);
  2061. } else {
  2062. pattern = FcNameParse((FcChar8 *)fontstr);
  2063. }
  2064. if(!pattern)
  2065. die("st: can't open font %s\n", fontstr);
  2066. if(fontsize > 0) {
  2067. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2068. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2069. usedfontsize = fontsize;
  2070. } else {
  2071. result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2072. if(result == FcResultMatch) {
  2073. usedfontsize = (int)fontval;
  2074. } else {
  2075. /*
  2076. * Default font size is 12, if none given. This is to
  2077. * have a known usedfontsize value.
  2078. */
  2079. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2080. usedfontsize = 12;
  2081. }
  2082. }
  2083. if(xloadfont(&dc.font, pattern))
  2084. die("st: can't open font %s\n", fontstr);
  2085. /* Setting character width and height. */
  2086. xw.cw = dc.font.width;
  2087. xw.ch = dc.font.height;
  2088. FcPatternDel(pattern, FC_WEIGHT);
  2089. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2090. if(xloadfont(&dc.bfont, pattern))
  2091. die("st: can't open font %s\n", fontstr);
  2092. FcPatternDel(pattern, FC_SLANT);
  2093. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2094. if(xloadfont(&dc.ibfont, pattern))
  2095. die("st: can't open font %s\n", fontstr);
  2096. FcPatternDel(pattern, FC_WEIGHT);
  2097. if(xloadfont(&dc.ifont, pattern))
  2098. die("st: can't open font %s\n", fontstr);
  2099. FcPatternDestroy(pattern);
  2100. }
  2101. void
  2102. xzoom(const Arg *arg)
  2103. {
  2104. xloadfonts(usedfont, usedfontsize + arg->i);
  2105. cresize(0, 0);
  2106. draw();
  2107. }
  2108. void
  2109. xinit(void) {
  2110. XSetWindowAttributes attrs;
  2111. Cursor cursor;
  2112. Window parent;
  2113. int sw, sh, major, minor;
  2114. if(!(xw.dpy = XOpenDisplay(NULL)))
  2115. die("Can't open display\n");
  2116. xw.scr = XDefaultScreen(xw.dpy);
  2117. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2118. /* font */
  2119. usedfont = (opt_font == NULL)? font : opt_font;
  2120. xloadfonts(usedfont, 0);
  2121. /* colors */
  2122. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2123. xloadcols();
  2124. /* adjust fixed window geometry */
  2125. if(xw.isfixed) {
  2126. sw = DisplayWidth(xw.dpy, xw.scr);
  2127. sh = DisplayHeight(xw.dpy, xw.scr);
  2128. if(xw.fx < 0)
  2129. xw.fx = sw + xw.fx - xw.fw - 1;
  2130. if(xw.fy < 0)
  2131. xw.fy = sh + xw.fy - xw.fh - 1;
  2132. xw.h = xw.fh;
  2133. xw.w = xw.fw;
  2134. } else {
  2135. /* window - default size */
  2136. xw.h = 2*borderpx + term.row * xw.ch;
  2137. xw.w = 2*borderpx + term.col * xw.cw;
  2138. xw.fx = 0;
  2139. xw.fy = 0;
  2140. }
  2141. attrs.background_pixel = dc.col[defaultbg].pixel;
  2142. attrs.border_pixel = dc.col[defaultbg].pixel;
  2143. attrs.bit_gravity = NorthWestGravity;
  2144. attrs.event_mask = FocusChangeMask | KeyPressMask
  2145. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2146. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2147. attrs.colormap = xw.cmap;
  2148. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  2149. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  2150. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2151. xw.vis,
  2152. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  2153. | CWColormap,
  2154. &attrs);
  2155. /* double buffering */
  2156. if(!XdbeQueryExtension(xw.dpy, &major, &minor))
  2157. die("Xdbe extension is not present\n");
  2158. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  2159. /* Xft rendering context */
  2160. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2161. /* input methods */
  2162. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  2163. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2164. | XIMStatusNothing, XNClientWindow, xw.win,
  2165. XNFocusWindow, xw.win, NULL);
  2166. /* white cursor, black outline */
  2167. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2168. XDefineCursor(xw.dpy, xw.win, cursor);
  2169. XRecolorCursor(xw.dpy, cursor,
  2170. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2171. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2172. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2173. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2174. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2175. xresettitle();
  2176. XMapWindow(xw.dpy, xw.win);
  2177. xhints();
  2178. XSync(xw.dpy, 0);
  2179. }
  2180. void
  2181. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2182. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2183. width = charlen * xw.cw;
  2184. Font *font = &dc.font;
  2185. XGlyphInfo extents;
  2186. Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
  2187. *temp, revfg, revbg;
  2188. XRenderColor colfg, colbg;
  2189. if(base.mode & ATTR_BOLD) {
  2190. if(BETWEEN(base.fg, 0, 7)) {
  2191. /* basic system colors */
  2192. fg = &dc.col[base.fg + 8];
  2193. } else if(BETWEEN(base.fg, 16, 195)) {
  2194. /* 256 colors */
  2195. fg = &dc.col[base.fg + 36];
  2196. } else if(BETWEEN(base.fg, 232, 251)) {
  2197. /* greyscale */
  2198. fg = &dc.col[base.fg + 4];
  2199. }
  2200. /*
  2201. * Those ranges will not be brightened:
  2202. * 8 - 15 bright system colors
  2203. * 196 - 231 highest 256 color cube
  2204. * 252 - 255 brightest colors in greyscale
  2205. */
  2206. font = &dc.bfont;
  2207. }
  2208. if(base.mode & ATTR_ITALIC)
  2209. font = &dc.ifont;
  2210. if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
  2211. font = &dc.ibfont;
  2212. if(IS_SET(MODE_REVERSE)) {
  2213. if(fg == &dc.col[defaultfg]) {
  2214. fg = &dc.col[defaultbg];
  2215. } else {
  2216. colfg.red = ~fg->color.red;
  2217. colfg.green = ~fg->color.green;
  2218. colfg.blue = ~fg->color.blue;
  2219. colfg.alpha = fg->color.alpha;
  2220. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2221. fg = &revfg;
  2222. }
  2223. if(bg == &dc.col[defaultbg]) {
  2224. bg = &dc.col[defaultfg];
  2225. } else {
  2226. colbg.red = ~bg->color.red;
  2227. colbg.green = ~bg->color.green;
  2228. colbg.blue = ~bg->color.blue;
  2229. colbg.alpha = bg->color.alpha;
  2230. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
  2231. bg = &revbg;
  2232. }
  2233. }
  2234. if(base.mode & ATTR_REVERSE)
  2235. temp = fg, fg = bg, bg = temp;
  2236. XftTextExtentsUtf8(xw.dpy, font->set, (FcChar8 *)s, bytelen,
  2237. &extents);
  2238. width = extents.xOff;
  2239. /* Intelligent cleaning up of the borders. */
  2240. if(x == 0) {
  2241. xclear(0, (y == 0)? 0 : winy, borderpx,
  2242. winy + xw.ch + (y == term.row-1)? xw.h : 0);
  2243. }
  2244. if(x + charlen >= term.col-1) {
  2245. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2246. (y == term.row-1)? xw.h : (winy + xw.ch));
  2247. }
  2248. if(y == 0)
  2249. xclear(winx, 0, winx + width, borderpx);
  2250. if(y == term.row-1)
  2251. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2252. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  2253. XftDrawStringUtf8(xw.draw, fg, font->set, winx,
  2254. winy + font->ascent, (FcChar8 *)s, bytelen);
  2255. if(base.mode & ATTR_UNDERLINE) {
  2256. XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
  2257. width, 1);
  2258. }
  2259. }
  2260. void
  2261. xdrawcursor(void) {
  2262. static int oldx = 0, oldy = 0;
  2263. int sl;
  2264. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
  2265. LIMIT(oldx, 0, term.col-1);
  2266. LIMIT(oldy, 0, term.row-1);
  2267. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  2268. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  2269. /* remove the old cursor */
  2270. if(term.line[oldy][oldx].state & GLYPH_SET) {
  2271. sl = utf8size(term.line[oldy][oldx].c);
  2272. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  2273. oldy, 1, sl);
  2274. } else {
  2275. xtermclear(oldx, oldy, oldx, oldy);
  2276. }
  2277. /* draw the new one */
  2278. if(!(IS_SET(MODE_HIDE))) {
  2279. if(!(xw.state & WIN_FOCUSED))
  2280. g.bg = defaultucs;
  2281. if(IS_SET(MODE_REVERSE))
  2282. g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
  2283. sl = utf8size(g.c);
  2284. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  2285. oldx = term.c.x, oldy = term.c.y;
  2286. }
  2287. }
  2288. void
  2289. xresettitle(void) {
  2290. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  2291. }
  2292. void
  2293. redraw(void) {
  2294. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  2295. tfulldirt();
  2296. draw();
  2297. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2298. nanosleep(&tv, NULL);
  2299. }
  2300. void
  2301. draw(void) {
  2302. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  2303. drawregion(0, 0, term.col, term.row);
  2304. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  2305. }
  2306. void
  2307. drawregion(int x1, int y1, int x2, int y2) {
  2308. int ic, ib, x, y, ox, sl;
  2309. Glyph base, new;
  2310. char buf[DRAW_BUF_SIZ];
  2311. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN) != 0;
  2312. if((sel.alt != 0) ^ alt)
  2313. ena_sel = 0;
  2314. if(!(xw.state & WIN_VISIBLE))
  2315. return;
  2316. for(y = y1; y < y2; y++) {
  2317. if(!term.dirty[y])
  2318. continue;
  2319. xtermclear(0, y, term.col, y);
  2320. term.dirty[y] = 0;
  2321. base = term.line[y][0];
  2322. ic = ib = ox = 0;
  2323. for(x = x1; x < x2; x++) {
  2324. new = term.line[y][x];
  2325. if(ena_sel && *(new.c) && selected(x, y))
  2326. new.mode ^= ATTR_REVERSE;
  2327. if(ib > 0 && (!(new.state & GLYPH_SET)
  2328. || ATTRCMP(base, new)
  2329. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  2330. xdraws(buf, base, ox, y, ic, ib);
  2331. ic = ib = 0;
  2332. }
  2333. if(new.state & GLYPH_SET) {
  2334. if(ib == 0) {
  2335. ox = x;
  2336. base = new;
  2337. }
  2338. sl = utf8size(new.c);
  2339. memcpy(buf+ib, new.c, sl);
  2340. ib += sl;
  2341. ++ic;
  2342. }
  2343. }
  2344. if(ib > 0)
  2345. xdraws(buf, base, ox, y, ic, ib);
  2346. }
  2347. xdrawcursor();
  2348. }
  2349. void
  2350. expose(XEvent *ev) {
  2351. XExposeEvent *e = &ev->xexpose;
  2352. if(xw.state & WIN_REDRAW) {
  2353. if(!e->count)
  2354. xw.state &= ~WIN_REDRAW;
  2355. }
  2356. }
  2357. void
  2358. visibility(XEvent *ev) {
  2359. XVisibilityEvent *e = &ev->xvisibility;
  2360. if(e->state == VisibilityFullyObscured) {
  2361. xw.state &= ~WIN_VISIBLE;
  2362. } else if(!(xw.state & WIN_VISIBLE)) {
  2363. /* need a full redraw for next Expose, not just a buf copy */
  2364. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2365. }
  2366. }
  2367. void
  2368. unmap(XEvent *ev) {
  2369. xw.state &= ~WIN_VISIBLE;
  2370. }
  2371. void
  2372. xseturgency(int add) {
  2373. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2374. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2375. XSetWMHints(xw.dpy, xw.win, h);
  2376. XFree(h);
  2377. }
  2378. void
  2379. focus(XEvent *ev) {
  2380. if(ev->type == FocusIn) {
  2381. XSetICFocus(xw.xic);
  2382. xw.state |= WIN_FOCUSED;
  2383. xseturgency(0);
  2384. } else {
  2385. XUnsetICFocus(xw.xic);
  2386. xw.state &= ~WIN_FOCUSED;
  2387. }
  2388. }
  2389. char*
  2390. kmap(KeySym k, uint state) {
  2391. uint mask;
  2392. Key *kp;
  2393. state &= ~Mod2Mask;
  2394. for(kp = key; kp < key + LEN(key); kp++) {
  2395. mask = kp->mask;
  2396. if(kp->k != k)
  2397. continue;
  2398. if((state & mask) != mask &&
  2399. (mask == XK_NO_MOD && state)) {
  2400. continue;
  2401. }
  2402. if((kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) ||
  2403. (kp->appkey > 0 && !IS_SET(MODE_APPKEYPAD))) {
  2404. continue;
  2405. }
  2406. if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
  2407. (kp->appcursor > 0 && !IS_SET(MODE_APPCURSOR))) {
  2408. continue;
  2409. }
  2410. if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
  2411. (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
  2412. continue;
  2413. }
  2414. return kp->s;
  2415. }
  2416. return NULL;
  2417. }
  2418. void
  2419. kpress(XEvent *ev) {
  2420. XKeyEvent *e = &ev->xkey;
  2421. KeySym ksym;
  2422. char xstr[31], buf[32], *customkey, *cp = buf;
  2423. int len, i;
  2424. Status status;
  2425. if (IS_SET(MODE_KBDLOCK))
  2426. return;
  2427. len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
  2428. /* 1. shortcuts */
  2429. for(i = 0; i < LEN(shortcuts); i++) {
  2430. if((ksym == shortcuts[i].keysym)
  2431. && (CLEANMASK(shortcuts[i].mod) == \
  2432. CLEANMASK(e->state))
  2433. && shortcuts[i].func) {
  2434. shortcuts[i].func(&(shortcuts[i].arg));
  2435. }
  2436. }
  2437. /* 2. custom keys from config.h */
  2438. if((customkey = kmap(ksym, e->state))) {
  2439. len = strlen(customkey);
  2440. memcpy(buf, customkey, len);
  2441. /* 2. hardcoded (overrides X lookup) */
  2442. } else {
  2443. if(len == 0)
  2444. return;
  2445. if (len == 1 && e->state & Mod1Mask)
  2446. *cp++ = '\033';
  2447. memcpy(cp, xstr, len);
  2448. len = cp - buf + len;
  2449. }
  2450. ttywrite(buf, len);
  2451. if(IS_SET(MODE_ECHO))
  2452. techo(buf, len);
  2453. }
  2454. void
  2455. cmessage(XEvent *e) {
  2456. /* See xembed specs
  2457. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2458. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2459. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2460. xw.state |= WIN_FOCUSED;
  2461. xseturgency(0);
  2462. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2463. xw.state &= ~WIN_FOCUSED;
  2464. }
  2465. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  2466. /* Send SIGHUP to shell */
  2467. kill(pid, SIGHUP);
  2468. exit(EXIT_SUCCESS);
  2469. }
  2470. }
  2471. void
  2472. cresize(int width, int height)
  2473. {
  2474. int col, row;
  2475. if(width != 0)
  2476. xw.w = width;
  2477. if(height != 0)
  2478. xw.h = height;
  2479. col = (xw.w - 2*borderpx) / xw.cw;
  2480. row = (xw.h - 2*borderpx) / xw.ch;
  2481. tresize(col, row);
  2482. xresize(col, row);
  2483. ttyresize();
  2484. }
  2485. void
  2486. resize(XEvent *e) {
  2487. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2488. return;
  2489. cresize(e->xconfigure.width, e->xconfigure.height);
  2490. }
  2491. void
  2492. run(void) {
  2493. XEvent ev;
  2494. fd_set rfd;
  2495. int xfd = XConnectionNumber(xw.dpy), i;
  2496. struct timeval drawtimeout, *tv = NULL;
  2497. for(i = 0;; i++) {
  2498. FD_ZERO(&rfd);
  2499. FD_SET(cmdfd, &rfd);
  2500. FD_SET(xfd, &rfd);
  2501. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  2502. if(errno == EINTR)
  2503. continue;
  2504. die("select failed: %s\n", SERRNO);
  2505. }
  2506. /*
  2507. * Stop after a certain number of reads so the user does not
  2508. * feel like the system is stuttering.
  2509. */
  2510. if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
  2511. ttyread();
  2512. /*
  2513. * Just wait a bit so it isn't disturbing the
  2514. * user and the system is able to write something.
  2515. */
  2516. drawtimeout.tv_sec = 0;
  2517. drawtimeout.tv_usec = 5;
  2518. tv = &drawtimeout;
  2519. continue;
  2520. }
  2521. i = 0;
  2522. tv = NULL;
  2523. while(XPending(xw.dpy)) {
  2524. XNextEvent(xw.dpy, &ev);
  2525. if(XFilterEvent(&ev, None))
  2526. continue;
  2527. if(handler[ev.type])
  2528. (handler[ev.type])(&ev);
  2529. }
  2530. draw();
  2531. XFlush(xw.dpy);
  2532. }
  2533. }
  2534. int
  2535. main(int argc, char *argv[]) {
  2536. int i, bitm, xr, yr;
  2537. uint wr, hr;
  2538. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2539. xw.isfixed = False;
  2540. for(i = 1; i < argc; i++) {
  2541. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2542. case 'c':
  2543. if(++i < argc)
  2544. opt_class = argv[i];
  2545. break;
  2546. case 'e':
  2547. /* eat all remaining arguments */
  2548. if(++i < argc)
  2549. opt_cmd = &argv[i];
  2550. goto run;
  2551. case 'f':
  2552. if(++i < argc)
  2553. opt_font = argv[i];
  2554. break;
  2555. case 'g':
  2556. if(++i >= argc)
  2557. break;
  2558. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2559. if(bitm & XValue)
  2560. xw.fx = xr;
  2561. if(bitm & YValue)
  2562. xw.fy = yr;
  2563. if(bitm & WidthValue)
  2564. xw.fw = (int)wr;
  2565. if(bitm & HeightValue)
  2566. xw.fh = (int)hr;
  2567. if(bitm & XNegative && xw.fx == 0)
  2568. xw.fx = -1;
  2569. if(bitm & XNegative && xw.fy == 0)
  2570. xw.fy = -1;
  2571. if(xw.fh != 0 && xw.fw != 0)
  2572. xw.isfixed = True;
  2573. break;
  2574. case 'o':
  2575. if(++i < argc)
  2576. opt_io = argv[i];
  2577. break;
  2578. case 't':
  2579. if(++i < argc)
  2580. opt_title = argv[i];
  2581. break;
  2582. case 'v':
  2583. default:
  2584. die(USAGE);
  2585. case 'w':
  2586. if(++i < argc)
  2587. opt_embed = argv[i];
  2588. break;
  2589. }
  2590. }
  2591. run:
  2592. setlocale(LC_CTYPE, "");
  2593. XSetLocaleModifiers("");
  2594. tnew(80, 24);
  2595. xinit();
  2596. ttynew();
  2597. selinit();
  2598. run();
  2599. return 0;
  2600. }