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.

3871 lines
85 KiB

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