My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3391 lines
73 KiB

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