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.

3878 lines
85 KiB

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