Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3627 lines
78 KiB

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