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.

3896 lines
85 KiB

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