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

3907 lines
86 KiB

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