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.

3902 lines
86 KiB

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