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.

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