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.

3997 lines
88 KiB

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