My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4059 lines
89 KiB

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