My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3699 lines
80 KiB

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