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.

2966 lines
64 KiB

12 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
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
14 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
13 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
14 years ago
14 years ago
12 years ago
13 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_ANY_MOD UINT_MAX
  58. #define XK_NO_MOD 0
  59. #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
  60. /* macros */
  61. #define SERRNO strerror(errno)
  62. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  63. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  64. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  65. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  66. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  67. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  68. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  69. #define IS_SET(flag) (term.mode & (flag))
  70. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
  71. #define VT102ID "\033[?6c"
  72. enum glyph_attribute {
  73. ATTR_NULL = 0,
  74. ATTR_REVERSE = 1,
  75. ATTR_UNDERLINE = 2,
  76. ATTR_BOLD = 4,
  77. ATTR_GFX = 8,
  78. ATTR_ITALIC = 16,
  79. ATTR_BLINK = 32,
  80. };
  81. enum cursor_movement {
  82. CURSOR_UP,
  83. CURSOR_DOWN,
  84. CURSOR_LEFT,
  85. CURSOR_RIGHT,
  86. CURSOR_SAVE,
  87. CURSOR_LOAD
  88. };
  89. enum cursor_state {
  90. CURSOR_DEFAULT = 0,
  91. CURSOR_WRAPNEXT = 1,
  92. CURSOR_ORIGIN = 2
  93. };
  94. enum glyph_state {
  95. GLYPH_SET = 1,
  96. GLYPH_DIRTY = 2
  97. };
  98. enum term_mode {
  99. MODE_WRAP = 1,
  100. MODE_INSERT = 2,
  101. MODE_APPKEYPAD = 4,
  102. MODE_ALTSCREEN = 8,
  103. MODE_CRLF = 16,
  104. MODE_MOUSEBTN = 32,
  105. MODE_MOUSEMOTION = 64,
  106. MODE_MOUSE = 32|64,
  107. MODE_REVERSE = 128,
  108. MODE_KBDLOCK = 256,
  109. MODE_HIDE = 512,
  110. MODE_ECHO = 1024,
  111. MODE_APPCURSOR = 2048
  112. };
  113. enum escape_state {
  114. ESC_START = 1,
  115. ESC_CSI = 2,
  116. ESC_STR = 4, /* DSC, OSC, PM, APC */
  117. ESC_ALTCHARSET = 8,
  118. ESC_STR_END = 16, /* a final string was encountered */
  119. ESC_TEST = 32, /* Enter in test mode */
  120. };
  121. enum window_state {
  122. WIN_VISIBLE = 1,
  123. WIN_REDRAW = 2,
  124. WIN_FOCUSED = 4
  125. };
  126. /* bit macro */
  127. #undef B0
  128. enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
  129. typedef unsigned char uchar;
  130. typedef unsigned int uint;
  131. typedef unsigned long ulong;
  132. typedef unsigned short ushort;
  133. typedef struct {
  134. char c[UTF_SIZ]; /* character code */
  135. uchar mode; /* attribute flags */
  136. ushort fg; /* foreground */
  137. ushort bg; /* background */
  138. uchar state; /* state flags */
  139. } Glyph;
  140. typedef Glyph* Line;
  141. typedef struct {
  142. Glyph attr; /* current char attributes */
  143. int x;
  144. int y;
  145. char state;
  146. } TCursor;
  147. /* CSI Escape sequence structs */
  148. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  149. typedef struct {
  150. char buf[ESC_BUF_SIZ]; /* raw string */
  151. int len; /* raw string length */
  152. char priv;
  153. int arg[ESC_ARG_SIZ];
  154. int narg; /* nb of args */
  155. char mode;
  156. } CSIEscape;
  157. /* STR Escape sequence structs */
  158. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  159. typedef struct {
  160. char type; /* ESC type ... */
  161. char buf[STR_BUF_SIZ]; /* raw string */
  162. int len; /* raw string length */
  163. char *args[STR_ARG_SIZ];
  164. int narg; /* nb of args */
  165. } STREscape;
  166. /* Internal representation of the screen */
  167. typedef struct {
  168. int row; /* nb row */
  169. int col; /* nb col */
  170. Line *line; /* screen */
  171. Line *alt; /* alternate screen */
  172. bool *dirty; /* dirtyness of lines */
  173. TCursor c; /* cursor */
  174. int top; /* top scroll limit */
  175. int bot; /* bottom scroll limit */
  176. int mode; /* terminal mode flags */
  177. int esc; /* escape state flags */
  178. bool *tabs;
  179. } Term;
  180. /* Purely graphic info */
  181. typedef struct {
  182. Display *dpy;
  183. Colourmap cmap;
  184. Window win;
  185. XdbeBackBuffer buf;
  186. Atom xembed, wmdeletewin;
  187. XIM xim;
  188. XIC xic;
  189. Draw draw;
  190. Visual *vis;
  191. int scr;
  192. bool isfixed; /* is fixed geometry? */
  193. int fx, fy, fw, fh; /* fixed geometry */
  194. int tw, th; /* tty width and height */
  195. int w; /* window width */
  196. int h; /* window height */
  197. int ch; /* char height */
  198. int cw; /* char width */
  199. char state; /* focus, redraw, visible */
  200. } XWindow;
  201. typedef struct {
  202. KeySym k;
  203. uint mask;
  204. char s[ESC_BUF_SIZ];
  205. /* three valued logic variables: 0 indifferent, 1 on, -1 off */
  206. signed char appkey; /* application keypad */
  207. signed char appcursor; /* application cursor */
  208. signed char crlf; /* crlf mode */
  209. } Key;
  210. /* TODO: use better name for vars... */
  211. typedef struct {
  212. int mode;
  213. int bx, by;
  214. int ex, ey;
  215. struct {
  216. int x, y;
  217. } b, e;
  218. char *clip;
  219. Atom xtarget;
  220. bool alt;
  221. struct timeval tclick1;
  222. struct timeval tclick2;
  223. } Selection;
  224. typedef union {
  225. int i;
  226. unsigned int ui;
  227. float f;
  228. const void *v;
  229. } Arg;
  230. typedef struct {
  231. unsigned int mod;
  232. KeySym keysym;
  233. void (*func)(const Arg *);
  234. const Arg arg;
  235. } Shortcut;
  236. /* function definitions used in config.h */
  237. static void xzoom(const Arg *);
  238. static void selpaste(const Arg *);
  239. /* Config.h for applying patches and the configuration. */
  240. #include "config.h"
  241. /* Font structure */
  242. typedef struct {
  243. int height;
  244. int width;
  245. int ascent;
  246. int descent;
  247. short lbearing;
  248. short rbearing;
  249. XftFont *set;
  250. } Font;
  251. /* Drawing Context */
  252. typedef struct {
  253. Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
  254. Font font, bfont, ifont, ibfont;
  255. } DC;
  256. static void die(const char *, ...);
  257. static void draw(void);
  258. static void redraw(void);
  259. static void drawregion(int, int, int, int);
  260. static void execsh(void);
  261. static void sigchld(int);
  262. static void run(void);
  263. static void csidump(void);
  264. static void csihandle(void);
  265. static void csiparse(void);
  266. static void csireset(void);
  267. static void strdump(void);
  268. static void strhandle(void);
  269. static void strparse(void);
  270. static void strreset(void);
  271. static void tclearregion(int, int, int, int);
  272. static void tcursor(int);
  273. static void tdeletechar(int);
  274. static void tdeleteline(int);
  275. static void tinsertblank(int);
  276. static void tinsertblankline(int);
  277. static void tmoveto(int, int);
  278. static void tmoveato(int x, int y);
  279. static void tnew(int, int);
  280. static void tnewline(int);
  281. static void tputtab(bool);
  282. static void tputc(char *, int);
  283. static void treset(void);
  284. static int tresize(int, int);
  285. static void tscrollup(int, int);
  286. static void tscrolldown(int, int);
  287. static void tsetattr(int*, int);
  288. static void tsetchar(char *, Glyph *, int, int);
  289. static void tsetscroll(int, int);
  290. static void tswapscreen(void);
  291. static void tsetdirt(int, int);
  292. static void tsetmode(bool, bool, int *, int);
  293. static void tfulldirt(void);
  294. static void techo(char *, int);
  295. static inline bool match(uint, uint);
  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. if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
  1886. memmove(&term.line[term.c.y][term.c.x+1],
  1887. &term.line[term.c.y][term.c.x],
  1888. (term.col - term.c.x - 1) * sizeof(Glyph));
  1889. }
  1890. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  1891. if(term.c.x+1 < term.col) {
  1892. tmoveto(term.c.x+1, term.c.y);
  1893. } else {
  1894. term.c.state |= CURSOR_WRAPNEXT;
  1895. }
  1896. }
  1897. int
  1898. tresize(int col, int row) {
  1899. int i, x;
  1900. int minrow = MIN(row, term.row);
  1901. int mincol = MIN(col, term.col);
  1902. int slide = term.c.y - row + 1;
  1903. bool *bp;
  1904. if(col < 1 || row < 1)
  1905. return 0;
  1906. /* free unneeded rows */
  1907. i = 0;
  1908. if(slide > 0) {
  1909. /* slide screen to keep cursor where we expect it -
  1910. * tscrollup would work here, but we can optimize to
  1911. * memmove because we're freeing the earlier lines */
  1912. for(/* i = 0 */; i < slide; i++) {
  1913. free(term.line[i]);
  1914. free(term.alt[i]);
  1915. }
  1916. memmove(term.line, term.line + slide, row * sizeof(Line));
  1917. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1918. }
  1919. for(i += row; i < term.row; i++) {
  1920. free(term.line[i]);
  1921. free(term.alt[i]);
  1922. }
  1923. /* resize to new height */
  1924. term.line = xrealloc(term.line, row * sizeof(Line));
  1925. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1926. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1927. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1928. /* resize each row to new width, zero-pad if needed */
  1929. for(i = 0; i < minrow; i++) {
  1930. term.dirty[i] = 1;
  1931. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1932. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1933. for(x = mincol; x < col; x++) {
  1934. term.line[i][x].state = 0;
  1935. term.alt[i][x].state = 0;
  1936. }
  1937. }
  1938. /* allocate any new rows */
  1939. for(/* i == minrow */; i < row; i++) {
  1940. term.dirty[i] = 1;
  1941. term.line[i] = xcalloc(col, sizeof(Glyph));
  1942. term.alt [i] = xcalloc(col, sizeof(Glyph));
  1943. }
  1944. if(col > term.col) {
  1945. bp = term.tabs + term.col;
  1946. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1947. while(--bp > term.tabs && !*bp)
  1948. /* nothing */ ;
  1949. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  1950. *bp = 1;
  1951. }
  1952. /* update terminal size */
  1953. term.col = col;
  1954. term.row = row;
  1955. /* reset scrolling region */
  1956. tsetscroll(0, row-1);
  1957. /* make use of the LIMIT in tmoveto */
  1958. tmoveto(term.c.x, term.c.y);
  1959. return (slide > 0);
  1960. }
  1961. void
  1962. xresize(int col, int row) {
  1963. xw.tw = MAX(1, 2*borderpx + col * xw.cw);
  1964. xw.th = MAX(1, 2*borderpx + row * xw.ch);
  1965. XftDrawChange(xw.draw, xw.buf);
  1966. }
  1967. void
  1968. xloadcols(void) {
  1969. int i, r, g, b;
  1970. XRenderColor color = { .alpha = 0 };
  1971. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1972. for(i = 0; i < LEN(colorname); i++) {
  1973. if(!colorname[i])
  1974. continue;
  1975. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
  1976. die("Could not allocate color '%s'\n", colorname[i]);
  1977. }
  1978. }
  1979. /* load colors [16-255] ; same colors as xterm */
  1980. for(i = 16, r = 0; r < 6; r++) {
  1981. for(g = 0; g < 6; g++) {
  1982. for(b = 0; b < 6; b++) {
  1983. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1984. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1985. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1986. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
  1987. die("Could not allocate color %d\n", i);
  1988. }
  1989. i++;
  1990. }
  1991. }
  1992. }
  1993. for(r = 0; r < 24; r++, i++) {
  1994. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1995. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
  1996. &dc.col[i])) {
  1997. die("Could not allocate color %d\n", i);
  1998. }
  1999. }
  2000. }
  2001. void
  2002. xtermclear(int col1, int row1, int col2, int row2) {
  2003. XftDrawRect(xw.draw,
  2004. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2005. borderpx + col1 * xw.cw,
  2006. borderpx + row1 * xw.ch,
  2007. (col2-col1+1) * xw.cw,
  2008. (row2-row1+1) * xw.ch);
  2009. }
  2010. /*
  2011. * Absolute coordinates.
  2012. */
  2013. void
  2014. xclear(int x1, int y1, int x2, int y2) {
  2015. XftDrawRect(xw.draw,
  2016. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2017. x1, y1, x2-x1, y2-y1);
  2018. }
  2019. void
  2020. xhints(void) {
  2021. XClassHint class = {opt_class ? opt_class : termname, termname};
  2022. XWMHints wm = {.flags = InputHint, .input = 1};
  2023. XSizeHints *sizeh = NULL;
  2024. sizeh = XAllocSizeHints();
  2025. if(xw.isfixed == False) {
  2026. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2027. sizeh->height = xw.h;
  2028. sizeh->width = xw.w;
  2029. sizeh->height_inc = xw.ch;
  2030. sizeh->width_inc = xw.cw;
  2031. sizeh->base_height = 2*borderpx;
  2032. sizeh->base_width = 2*borderpx;
  2033. } else {
  2034. sizeh->flags = PMaxSize | PMinSize;
  2035. sizeh->min_width = sizeh->max_width = xw.fw;
  2036. sizeh->min_height = sizeh->max_height = xw.fh;
  2037. }
  2038. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  2039. XFree(sizeh);
  2040. }
  2041. int
  2042. xloadfont(Font *f, FcPattern *pattern) {
  2043. FcPattern *match;
  2044. FcResult result;
  2045. match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
  2046. if(!match)
  2047. return 1;
  2048. if(!(f->set = XftFontOpenPattern(xw.dpy, match))) {
  2049. FcPatternDestroy(match);
  2050. return 1;
  2051. }
  2052. f->ascent = f->set->ascent;
  2053. f->descent = f->set->descent;
  2054. f->lbearing = 0;
  2055. f->rbearing = f->set->max_advance_width;
  2056. f->height = f->set->height;
  2057. f->width = f->lbearing + f->rbearing;
  2058. return 0;
  2059. }
  2060. void
  2061. xloadfonts(char *fontstr, int fontsize) {
  2062. FcPattern *pattern;
  2063. FcResult result;
  2064. double fontval;
  2065. if(fontstr[0] == '-') {
  2066. pattern = XftXlfdParse(fontstr, False, False);
  2067. } else {
  2068. pattern = FcNameParse((FcChar8 *)fontstr);
  2069. }
  2070. if(!pattern)
  2071. die("st: can't open font %s\n", fontstr);
  2072. if(fontsize > 0) {
  2073. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2074. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2075. usedfontsize = fontsize;
  2076. } else {
  2077. result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2078. if(result == FcResultMatch) {
  2079. usedfontsize = (int)fontval;
  2080. } else {
  2081. /*
  2082. * Default font size is 12, if none given. This is to
  2083. * have a known usedfontsize value.
  2084. */
  2085. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2086. usedfontsize = 12;
  2087. }
  2088. }
  2089. if(xloadfont(&dc.font, pattern))
  2090. die("st: can't open font %s\n", fontstr);
  2091. /* Setting character width and height. */
  2092. xw.cw = dc.font.width;
  2093. xw.ch = dc.font.height;
  2094. FcPatternDel(pattern, FC_WEIGHT);
  2095. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2096. if(xloadfont(&dc.bfont, pattern))
  2097. die("st: can't open font %s\n", fontstr);
  2098. FcPatternDel(pattern, FC_SLANT);
  2099. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2100. if(xloadfont(&dc.ibfont, pattern))
  2101. die("st: can't open font %s\n", fontstr);
  2102. FcPatternDel(pattern, FC_WEIGHT);
  2103. if(xloadfont(&dc.ifont, pattern))
  2104. die("st: can't open font %s\n", fontstr);
  2105. FcPatternDestroy(pattern);
  2106. }
  2107. void
  2108. xzoom(const Arg *arg)
  2109. {
  2110. xloadfonts(usedfont, usedfontsize + arg->i);
  2111. cresize(0, 0);
  2112. draw();
  2113. }
  2114. void
  2115. xinit(void) {
  2116. XSetWindowAttributes attrs;
  2117. Cursor cursor;
  2118. Window parent;
  2119. int sw, sh, major, minor;
  2120. if(!(xw.dpy = XOpenDisplay(NULL)))
  2121. die("Can't open display\n");
  2122. xw.scr = XDefaultScreen(xw.dpy);
  2123. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2124. /* font */
  2125. usedfont = (opt_font == NULL)? font : opt_font;
  2126. xloadfonts(usedfont, 0);
  2127. /* colors */
  2128. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2129. xloadcols();
  2130. /* adjust fixed window geometry */
  2131. if(xw.isfixed) {
  2132. sw = DisplayWidth(xw.dpy, xw.scr);
  2133. sh = DisplayHeight(xw.dpy, xw.scr);
  2134. if(xw.fx < 0)
  2135. xw.fx = sw + xw.fx - xw.fw - 1;
  2136. if(xw.fy < 0)
  2137. xw.fy = sh + xw.fy - xw.fh - 1;
  2138. xw.h = xw.fh;
  2139. xw.w = xw.fw;
  2140. } else {
  2141. /* window - default size */
  2142. xw.h = 2*borderpx + term.row * xw.ch;
  2143. xw.w = 2*borderpx + term.col * xw.cw;
  2144. xw.fx = 0;
  2145. xw.fy = 0;
  2146. }
  2147. attrs.background_pixel = dc.col[defaultbg].pixel;
  2148. attrs.border_pixel = dc.col[defaultbg].pixel;
  2149. attrs.bit_gravity = NorthWestGravity;
  2150. attrs.event_mask = FocusChangeMask | KeyPressMask
  2151. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2152. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2153. attrs.colormap = xw.cmap;
  2154. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  2155. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  2156. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2157. xw.vis,
  2158. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  2159. | CWColormap,
  2160. &attrs);
  2161. /* double buffering */
  2162. if(!XdbeQueryExtension(xw.dpy, &major, &minor))
  2163. die("Xdbe extension is not present\n");
  2164. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  2165. /* Xft rendering context */
  2166. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2167. /* input methods */
  2168. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  2169. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2170. | XIMStatusNothing, XNClientWindow, xw.win,
  2171. XNFocusWindow, xw.win, NULL);
  2172. /* white cursor, black outline */
  2173. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2174. XDefineCursor(xw.dpy, xw.win, cursor);
  2175. XRecolorCursor(xw.dpy, cursor,
  2176. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2177. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2178. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2179. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2180. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2181. xresettitle();
  2182. XMapWindow(xw.dpy, xw.win);
  2183. xhints();
  2184. XSync(xw.dpy, 0);
  2185. }
  2186. void
  2187. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2188. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2189. width = charlen * xw.cw;
  2190. Font *font = &dc.font;
  2191. XGlyphInfo extents;
  2192. Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
  2193. *temp, revfg, revbg;
  2194. XRenderColor colfg, colbg;
  2195. if(base.mode & ATTR_BOLD) {
  2196. if(BETWEEN(base.fg, 0, 7)) {
  2197. /* basic system colors */
  2198. fg = &dc.col[base.fg + 8];
  2199. } else if(BETWEEN(base.fg, 16, 195)) {
  2200. /* 256 colors */
  2201. fg = &dc.col[base.fg + 36];
  2202. } else if(BETWEEN(base.fg, 232, 251)) {
  2203. /* greyscale */
  2204. fg = &dc.col[base.fg + 4];
  2205. }
  2206. /*
  2207. * Those ranges will not be brightened:
  2208. * 8 - 15 bright system colors
  2209. * 196 - 231 highest 256 color cube
  2210. * 252 - 255 brightest colors in greyscale
  2211. */
  2212. font = &dc.bfont;
  2213. }
  2214. if(base.mode & ATTR_ITALIC)
  2215. font = &dc.ifont;
  2216. if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
  2217. font = &dc.ibfont;
  2218. if(IS_SET(MODE_REVERSE)) {
  2219. if(fg == &dc.col[defaultfg]) {
  2220. fg = &dc.col[defaultbg];
  2221. } else {
  2222. colfg.red = ~fg->color.red;
  2223. colfg.green = ~fg->color.green;
  2224. colfg.blue = ~fg->color.blue;
  2225. colfg.alpha = fg->color.alpha;
  2226. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2227. fg = &revfg;
  2228. }
  2229. if(bg == &dc.col[defaultbg]) {
  2230. bg = &dc.col[defaultfg];
  2231. } else {
  2232. colbg.red = ~bg->color.red;
  2233. colbg.green = ~bg->color.green;
  2234. colbg.blue = ~bg->color.blue;
  2235. colbg.alpha = bg->color.alpha;
  2236. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
  2237. bg = &revbg;
  2238. }
  2239. }
  2240. if(base.mode & ATTR_REVERSE)
  2241. temp = fg, fg = bg, bg = temp;
  2242. XftTextExtentsUtf8(xw.dpy, font->set, (FcChar8 *)s, bytelen,
  2243. &extents);
  2244. width = extents.xOff;
  2245. /* Intelligent cleaning up of the borders. */
  2246. if(x == 0) {
  2247. xclear(0, (y == 0)? 0 : winy, borderpx,
  2248. winy + xw.ch + (y == term.row-1)? xw.h : 0);
  2249. }
  2250. if(x + charlen >= term.col-1) {
  2251. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2252. (y == term.row-1)? xw.h : (winy + xw.ch));
  2253. }
  2254. if(y == 0)
  2255. xclear(winx, 0, winx + width, borderpx);
  2256. if(y == term.row-1)
  2257. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2258. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  2259. XftDrawStringUtf8(xw.draw, fg, font->set, winx,
  2260. winy + font->ascent, (FcChar8 *)s, bytelen);
  2261. if(base.mode & ATTR_UNDERLINE) {
  2262. XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
  2263. width, 1);
  2264. }
  2265. }
  2266. void
  2267. xdrawcursor(void) {
  2268. static int oldx = 0, oldy = 0;
  2269. int sl;
  2270. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
  2271. LIMIT(oldx, 0, term.col-1);
  2272. LIMIT(oldy, 0, term.row-1);
  2273. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  2274. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  2275. /* remove the old cursor */
  2276. if(term.line[oldy][oldx].state & GLYPH_SET) {
  2277. sl = utf8size(term.line[oldy][oldx].c);
  2278. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  2279. oldy, 1, sl);
  2280. } else {
  2281. xtermclear(oldx, oldy, oldx, oldy);
  2282. }
  2283. /* draw the new one */
  2284. if(!(IS_SET(MODE_HIDE))) {
  2285. if(!(xw.state & WIN_FOCUSED))
  2286. g.bg = defaultucs;
  2287. if(IS_SET(MODE_REVERSE))
  2288. g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
  2289. sl = utf8size(g.c);
  2290. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  2291. oldx = term.c.x, oldy = term.c.y;
  2292. }
  2293. }
  2294. void
  2295. xresettitle(void) {
  2296. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  2297. }
  2298. void
  2299. redraw(void) {
  2300. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  2301. tfulldirt();
  2302. draw();
  2303. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2304. nanosleep(&tv, NULL);
  2305. }
  2306. void
  2307. draw(void) {
  2308. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  2309. drawregion(0, 0, term.col, term.row);
  2310. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  2311. }
  2312. void
  2313. drawregion(int x1, int y1, int x2, int y2) {
  2314. int ic, ib, x, y, ox, sl;
  2315. Glyph base, new;
  2316. char buf[DRAW_BUF_SIZ];
  2317. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN) != 0;
  2318. if((sel.alt != 0) ^ alt)
  2319. ena_sel = 0;
  2320. if(!(xw.state & WIN_VISIBLE))
  2321. return;
  2322. for(y = y1; y < y2; y++) {
  2323. if(!term.dirty[y])
  2324. continue;
  2325. xtermclear(0, y, term.col, y);
  2326. term.dirty[y] = 0;
  2327. base = term.line[y][0];
  2328. ic = ib = ox = 0;
  2329. for(x = x1; x < x2; x++) {
  2330. new = term.line[y][x];
  2331. if(ena_sel && *(new.c) && selected(x, y))
  2332. new.mode ^= ATTR_REVERSE;
  2333. if(ib > 0 && (!(new.state & GLYPH_SET)
  2334. || ATTRCMP(base, new)
  2335. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  2336. xdraws(buf, base, ox, y, ic, ib);
  2337. ic = ib = 0;
  2338. }
  2339. if(new.state & GLYPH_SET) {
  2340. if(ib == 0) {
  2341. ox = x;
  2342. base = new;
  2343. }
  2344. sl = utf8size(new.c);
  2345. memcpy(buf+ib, new.c, sl);
  2346. ib += sl;
  2347. ++ic;
  2348. }
  2349. }
  2350. if(ib > 0)
  2351. xdraws(buf, base, ox, y, ic, ib);
  2352. }
  2353. xdrawcursor();
  2354. }
  2355. void
  2356. expose(XEvent *ev) {
  2357. XExposeEvent *e = &ev->xexpose;
  2358. if(xw.state & WIN_REDRAW) {
  2359. if(!e->count)
  2360. xw.state &= ~WIN_REDRAW;
  2361. }
  2362. }
  2363. void
  2364. visibility(XEvent *ev) {
  2365. XVisibilityEvent *e = &ev->xvisibility;
  2366. if(e->state == VisibilityFullyObscured) {
  2367. xw.state &= ~WIN_VISIBLE;
  2368. } else if(!(xw.state & WIN_VISIBLE)) {
  2369. /* need a full redraw for next Expose, not just a buf copy */
  2370. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2371. }
  2372. }
  2373. void
  2374. unmap(XEvent *ev) {
  2375. xw.state &= ~WIN_VISIBLE;
  2376. }
  2377. void
  2378. xseturgency(int add) {
  2379. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2380. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2381. XSetWMHints(xw.dpy, xw.win, h);
  2382. XFree(h);
  2383. }
  2384. void
  2385. focus(XEvent *ev) {
  2386. if(ev->type == FocusIn) {
  2387. XSetICFocus(xw.xic);
  2388. xw.state |= WIN_FOCUSED;
  2389. xseturgency(0);
  2390. } else {
  2391. XUnsetICFocus(xw.xic);
  2392. xw.state &= ~WIN_FOCUSED;
  2393. }
  2394. }
  2395. inline bool
  2396. match(uint mask, uint state) {
  2397. if(mask == XK_NO_MOD && state)
  2398. return false;
  2399. if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
  2400. return false;
  2401. if((state & mask) != state)
  2402. return false;
  2403. return true;
  2404. }
  2405. char*
  2406. kmap(KeySym k, uint state) {
  2407. uint mask;
  2408. Key *kp;
  2409. int i;
  2410. /* Check for mapped keys out of X11 function keys. */
  2411. for(i = 0; i < LEN(mappedkeys); i++) {
  2412. if(mappedkeys[i] == k)
  2413. break;
  2414. }
  2415. if(i == LEN(mappedkeys)) {
  2416. if((k & 0xFFFF) < 0xFF00)
  2417. return NULL;
  2418. }
  2419. for(kp = key; kp < key + LEN(key); kp++) {
  2420. mask = kp->mask;
  2421. if(kp->k != k)
  2422. continue;
  2423. if(!match(mask, state))
  2424. continue;
  2425. if((kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) ||
  2426. (kp->appkey > 0 && !IS_SET(MODE_APPKEYPAD))) {
  2427. continue;
  2428. }
  2429. if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
  2430. (kp->appcursor > 0 && !IS_SET(MODE_APPCURSOR))) {
  2431. continue;
  2432. }
  2433. if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
  2434. (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
  2435. continue;
  2436. }
  2437. return kp->s;
  2438. }
  2439. return NULL;
  2440. }
  2441. void
  2442. kpress(XEvent *ev) {
  2443. XKeyEvent *e = &ev->xkey;
  2444. KeySym ksym;
  2445. char xstr[31], buf[32], *customkey, *cp = buf;
  2446. int len;
  2447. Status status;
  2448. Shortcut *bp;
  2449. if (IS_SET(MODE_KBDLOCK))
  2450. return;
  2451. len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
  2452. e->state &= ~Mod2Mask;
  2453. /* 1. shortcuts */
  2454. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  2455. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  2456. bp->func(&(bp->arg));
  2457. return;
  2458. }
  2459. }
  2460. /* 2. custom keys from config.h */
  2461. if((customkey = kmap(ksym, e->state))) {
  2462. len = strlen(customkey);
  2463. memcpy(buf, customkey, len);
  2464. /* 2. hardcoded (overrides X lookup) */
  2465. } else {
  2466. if(len == 0)
  2467. return;
  2468. if (len == 1 && e->state & Mod1Mask)
  2469. *cp++ = '\033';
  2470. memcpy(cp, xstr, len);
  2471. len = cp - buf + len;
  2472. }
  2473. ttywrite(buf, len);
  2474. if(IS_SET(MODE_ECHO))
  2475. techo(buf, len);
  2476. }
  2477. void
  2478. cmessage(XEvent *e) {
  2479. /* See xembed specs
  2480. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2481. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2482. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2483. xw.state |= WIN_FOCUSED;
  2484. xseturgency(0);
  2485. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2486. xw.state &= ~WIN_FOCUSED;
  2487. }
  2488. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  2489. /* Send SIGHUP to shell */
  2490. kill(pid, SIGHUP);
  2491. exit(EXIT_SUCCESS);
  2492. }
  2493. }
  2494. void
  2495. cresize(int width, int height)
  2496. {
  2497. int col, row;
  2498. if(width != 0)
  2499. xw.w = width;
  2500. if(height != 0)
  2501. xw.h = height;
  2502. col = (xw.w - 2*borderpx) / xw.cw;
  2503. row = (xw.h - 2*borderpx) / xw.ch;
  2504. tresize(col, row);
  2505. xresize(col, row);
  2506. ttyresize();
  2507. }
  2508. void
  2509. resize(XEvent *e) {
  2510. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2511. return;
  2512. cresize(e->xconfigure.width, e->xconfigure.height);
  2513. }
  2514. void
  2515. run(void) {
  2516. XEvent ev;
  2517. fd_set rfd;
  2518. int xfd = XConnectionNumber(xw.dpy), i;
  2519. struct timeval drawtimeout, *tv = NULL;
  2520. for(i = 0;; i++) {
  2521. FD_ZERO(&rfd);
  2522. FD_SET(cmdfd, &rfd);
  2523. FD_SET(xfd, &rfd);
  2524. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  2525. if(errno == EINTR)
  2526. continue;
  2527. die("select failed: %s\n", SERRNO);
  2528. }
  2529. /*
  2530. * Stop after a certain number of reads so the user does not
  2531. * feel like the system is stuttering.
  2532. */
  2533. if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
  2534. ttyread();
  2535. /*
  2536. * Just wait a bit so it isn't disturbing the
  2537. * user and the system is able to write something.
  2538. */
  2539. drawtimeout.tv_sec = 0;
  2540. drawtimeout.tv_usec = 5;
  2541. tv = &drawtimeout;
  2542. continue;
  2543. }
  2544. i = 0;
  2545. tv = NULL;
  2546. while(XPending(xw.dpy)) {
  2547. XNextEvent(xw.dpy, &ev);
  2548. if(XFilterEvent(&ev, None))
  2549. continue;
  2550. if(handler[ev.type])
  2551. (handler[ev.type])(&ev);
  2552. }
  2553. draw();
  2554. XFlush(xw.dpy);
  2555. }
  2556. }
  2557. int
  2558. main(int argc, char *argv[]) {
  2559. int i, bitm, xr, yr;
  2560. uint wr, hr;
  2561. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2562. xw.isfixed = False;
  2563. for(i = 1; i < argc; i++) {
  2564. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2565. case 'c':
  2566. if(++i < argc)
  2567. opt_class = argv[i];
  2568. break;
  2569. case 'e':
  2570. /* eat all remaining arguments */
  2571. if(++i < argc)
  2572. opt_cmd = &argv[i];
  2573. goto run;
  2574. case 'f':
  2575. if(++i < argc)
  2576. opt_font = argv[i];
  2577. break;
  2578. case 'g':
  2579. if(++i >= argc)
  2580. break;
  2581. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2582. if(bitm & XValue)
  2583. xw.fx = xr;
  2584. if(bitm & YValue)
  2585. xw.fy = yr;
  2586. if(bitm & WidthValue)
  2587. xw.fw = (int)wr;
  2588. if(bitm & HeightValue)
  2589. xw.fh = (int)hr;
  2590. if(bitm & XNegative && xw.fx == 0)
  2591. xw.fx = -1;
  2592. if(bitm & XNegative && xw.fy == 0)
  2593. xw.fy = -1;
  2594. if(xw.fh != 0 && xw.fw != 0)
  2595. xw.isfixed = True;
  2596. break;
  2597. case 'o':
  2598. if(++i < argc)
  2599. opt_io = argv[i];
  2600. break;
  2601. case 't':
  2602. if(++i < argc)
  2603. opt_title = argv[i];
  2604. break;
  2605. case 'v':
  2606. default:
  2607. die(USAGE);
  2608. case 'w':
  2609. if(++i < argc)
  2610. opt_embed = argv[i];
  2611. break;
  2612. }
  2613. }
  2614. run:
  2615. setlocale(LC_CTYPE, "");
  2616. XSetLocaleModifiers("");
  2617. tnew(80, 24);
  2618. xinit();
  2619. ttynew();
  2620. selinit();
  2621. run();
  2622. return 0;
  2623. }