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

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