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.

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