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.

3641 lines
78 KiB

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