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.

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