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.

3841 lines
84 KiB

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