Simple Terminal from SuckLess
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.

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