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.

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