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.

3391 lines
74 KiB

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