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.

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