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.

3740 lines
81 KiB

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