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.

3293 lines
71 KiB

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