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

3285 lines
71 KiB

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