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.

3736 lines
81 KiB

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