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.

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