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.

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