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.

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