Simple Terminal from SuckLess
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.

3872 lines
85 KiB

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