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.

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