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.

3290 lines
71 KiB

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