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

3660 lines
78 KiB

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