Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2980 lines
65 KiB

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