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.

3863 lines
84 KiB

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