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.

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