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.

3731 lines
81 KiB

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