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

3999 lines
88 KiB

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