Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4063 lines
89 KiB

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