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.

3954 lines
87 KiB

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