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.

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