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.

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