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

3376 lines
73 KiB

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