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

2558 lines
57 KiB

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
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
15 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
  1. /* See LICENSE for licence details. */
  2. #define _XOPEN_SOURCE 600
  3. #include <ctype.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <limits.h>
  7. #include <locale.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/extensions/Xdbe.h>
  28. #include <X11/Xft/Xft.h>
  29. #define Glyph Glyph_
  30. #define Font Font_
  31. #if defined(__linux)
  32. #include <pty.h>
  33. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  34. #include <util.h>
  35. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  36. #include <libutil.h>
  37. #endif
  38. #define USAGE \
  39. "st " VERSION " (c) 2010-2012 st engineers\n" \
  40. "usage: st [-t title] [-c class] [-g geometry]" \
  41. " [-w windowid] [-v] [-f file] [-e command...]\n"
  42. /* XEMBED messages */
  43. #define XEMBED_FOCUS_IN 4
  44. #define XEMBED_FOCUS_OUT 5
  45. /* Arbitrary sizes */
  46. #define ESC_BUF_SIZ 256
  47. #define ESC_ARG_SIZ 16
  48. #define STR_BUF_SIZ 256
  49. #define STR_ARG_SIZ 16
  50. #define DRAW_BUF_SIZ 20*1024
  51. #define UTF_SIZ 4
  52. #define XK_NO_MOD UINT_MAX
  53. #define XK_ANY_MOD 0
  54. #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
  55. #define SERRNO strerror(errno)
  56. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  57. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  58. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  59. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  60. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  61. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  62. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  63. #define IS_SET(flag) (term.mode & (flag))
  64. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
  65. #define X2COL(x) (((x) - BORDER)/xw.cw)
  66. #define Y2ROW(y) (((y) - BORDER)/xw.ch)
  67. enum glyph_attribute {
  68. ATTR_NULL = 0,
  69. ATTR_REVERSE = 1,
  70. ATTR_UNDERLINE = 2,
  71. ATTR_BOLD = 4,
  72. ATTR_GFX = 8,
  73. ATTR_ITALIC = 16,
  74. ATTR_BLINK = 32,
  75. };
  76. enum cursor_movement {
  77. CURSOR_UP,
  78. CURSOR_DOWN,
  79. CURSOR_LEFT,
  80. CURSOR_RIGHT,
  81. CURSOR_SAVE,
  82. CURSOR_LOAD
  83. };
  84. enum cursor_state {
  85. CURSOR_DEFAULT = 0,
  86. CURSOR_HIDE = 1,
  87. CURSOR_WRAPNEXT = 2
  88. };
  89. enum glyph_state {
  90. GLYPH_SET = 1,
  91. GLYPH_DIRTY = 2
  92. };
  93. enum term_mode {
  94. MODE_WRAP = 1,
  95. MODE_INSERT = 2,
  96. MODE_APPKEYPAD = 4,
  97. MODE_ALTSCREEN = 8,
  98. MODE_CRLF = 16,
  99. MODE_MOUSEBTN = 32,
  100. MODE_MOUSEMOTION = 64,
  101. MODE_MOUSE = 32|64,
  102. MODE_REVERSE = 128,
  103. MODE_KBDLOCK = 256
  104. };
  105. enum escape_state {
  106. ESC_START = 1,
  107. ESC_CSI = 2,
  108. ESC_STR = 4, /* DSC, OSC, PM, APC */
  109. ESC_ALTCHARSET = 8,
  110. ESC_STR_END = 16, /* a final string was encountered */
  111. };
  112. enum window_state {
  113. WIN_VISIBLE = 1,
  114. WIN_REDRAW = 2,
  115. WIN_FOCUSED = 4
  116. };
  117. /* bit macro */
  118. #undef B0
  119. enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
  120. typedef unsigned char uchar;
  121. typedef unsigned int uint;
  122. typedef unsigned long ulong;
  123. typedef unsigned short ushort;
  124. typedef struct {
  125. char c[UTF_SIZ]; /* character code */
  126. uchar mode; /* attribute flags */
  127. ushort fg; /* foreground */
  128. ushort bg; /* background */
  129. uchar state; /* state flags */
  130. } Glyph;
  131. typedef Glyph* Line;
  132. typedef struct {
  133. Glyph attr; /* current char attributes */
  134. int x;
  135. int y;
  136. char state;
  137. } TCursor;
  138. /* CSI Escape sequence structs */
  139. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  140. typedef struct {
  141. char buf[ESC_BUF_SIZ]; /* raw string */
  142. int len; /* raw string length */
  143. char priv;
  144. int arg[ESC_ARG_SIZ];
  145. int narg; /* nb of args */
  146. char mode;
  147. } CSIEscape;
  148. /* STR Escape sequence structs */
  149. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  150. typedef struct {
  151. char type; /* ESC type ... */
  152. char buf[STR_BUF_SIZ]; /* raw string */
  153. int len; /* raw string length */
  154. char *args[STR_ARG_SIZ];
  155. int narg; /* nb of args */
  156. } STREscape;
  157. /* Internal representation of the screen */
  158. typedef struct {
  159. int row; /* nb row */
  160. int col; /* nb col */
  161. Line* line; /* screen */
  162. Line* alt; /* alternate screen */
  163. bool* dirty; /* dirtyness of lines */
  164. TCursor c; /* cursor */
  165. int top; /* top scroll limit */
  166. int bot; /* bottom scroll limit */
  167. int mode; /* terminal mode flags */
  168. int esc; /* escape state flags */
  169. bool *tabs;
  170. } Term;
  171. /* Purely graphic info */
  172. typedef struct {
  173. Display* dpy;
  174. Colormap cmap;
  175. Window win;
  176. XdbeBackBuffer buf;
  177. Atom xembed;
  178. XIM xim;
  179. XIC xic;
  180. XftDraw *xft_draw;
  181. Visual *vis;
  182. int scr;
  183. bool isfixed; /* is fixed geometry? */
  184. int fx, fy, fw, fh; /* fixed geometry */
  185. int tw, th; /* tty width and height */
  186. int w; /* window width */
  187. int h; /* window height */
  188. int ch; /* char height */
  189. int cw; /* char width */
  190. char state; /* focus, redraw, visible */
  191. } XWindow;
  192. typedef struct {
  193. KeySym k;
  194. uint mask;
  195. char s[ESC_BUF_SIZ];
  196. } Key;
  197. /* TODO: use better name for vars... */
  198. typedef struct {
  199. int mode;
  200. int bx, by;
  201. int ex, ey;
  202. struct {int x, y;} b, e;
  203. char *clip;
  204. Atom xtarget;
  205. bool alt;
  206. struct timeval tclick1;
  207. struct timeval tclick2;
  208. } Selection;
  209. #include "config.h"
  210. /* Font structure */
  211. typedef struct {
  212. int ascent;
  213. int descent;
  214. short lbearing;
  215. short rbearing;
  216. XftFont* xft_set;
  217. } Font;
  218. /* Drawing Context */
  219. typedef struct {
  220. XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
  221. GC gc;
  222. Font font, bfont, ifont, ibfont;
  223. } DC;
  224. static void die(const char*, ...);
  225. static void draw(void);
  226. static void redraw(void);
  227. static void drawregion(int, int, int, int);
  228. static void execsh(void);
  229. static void sigchld(int);
  230. static void run(void);
  231. static void csidump(void);
  232. static void csihandle(void);
  233. static void csiparse(void);
  234. static void csireset(void);
  235. static void strdump(void);
  236. static void strhandle(void);
  237. static void strparse(void);
  238. static void strreset(void);
  239. static void tclearregion(int, int, int, int);
  240. static void tcursor(int);
  241. static void tdeletechar(int);
  242. static void tdeleteline(int);
  243. static void tinsertblank(int);
  244. static void tinsertblankline(int);
  245. static void tmoveto(int, int);
  246. static void tnew(int, int);
  247. static void tnewline(int);
  248. static void tputtab(bool);
  249. static void tputc(char*, int);
  250. static void treset(void);
  251. static int tresize(int, int);
  252. static void tscrollup(int, int);
  253. static void tscrolldown(int, int);
  254. static void tsetattr(int*, int);
  255. static void tsetchar(char*);
  256. static void tsetscroll(int, int);
  257. static void tswapscreen(void);
  258. static void tsetdirt(int, int);
  259. static void tsetmode(bool, bool, int *, int);
  260. static void tfulldirt(void);
  261. static void ttynew(void);
  262. static void ttyread(void);
  263. static void ttyresize(void);
  264. static void ttywrite(const char *, size_t);
  265. static void xdraws(char *, Glyph, int, int, int, int);
  266. static void xhints(void);
  267. static void xclear(int, int, int, int);
  268. static void xclearborders(void);
  269. static void xdrawcursor(void);
  270. static void xinit(void);
  271. static void xloadcols(void);
  272. static void xresettitle(void);
  273. static void xseturgency(int);
  274. static void xsetsel(char*);
  275. static void xtermclear(int, int, int, int);
  276. static void xresize(int, int);
  277. static void expose(XEvent *);
  278. static void visibility(XEvent *);
  279. static void unmap(XEvent *);
  280. static char* kmap(KeySym, uint);
  281. static void kpress(XEvent *);
  282. static void cmessage(XEvent *);
  283. static void resize(XEvent *);
  284. static void focus(XEvent *);
  285. static void brelease(XEvent *);
  286. static void bpress(XEvent *);
  287. static void bmotion(XEvent *);
  288. static void selnotify(XEvent *);
  289. static void selclear(XEvent *);
  290. static void selrequest(XEvent *);
  291. static void selinit(void);
  292. static inline bool selected(int, int);
  293. static void selcopy(void);
  294. static void selpaste(void);
  295. static void selscroll(int, int);
  296. static int utf8decode(char *, long *);
  297. static int utf8encode(long *, char *);
  298. static int utf8size(char *);
  299. static int isfullutf8(char *, int);
  300. static void *xmalloc(size_t);
  301. static void *xrealloc(void *, size_t);
  302. static void *xcalloc(size_t nmemb, size_t size);
  303. static char *smstrcat(char *, ...);
  304. static void (*handler[LASTEvent])(XEvent *) = {
  305. [KeyPress] = kpress,
  306. [ClientMessage] = cmessage,
  307. [ConfigureNotify] = resize,
  308. [VisibilityNotify] = visibility,
  309. [UnmapNotify] = unmap,
  310. [Expose] = expose,
  311. [FocusIn] = focus,
  312. [FocusOut] = focus,
  313. [MotionNotify] = bmotion,
  314. [ButtonPress] = bpress,
  315. [ButtonRelease] = brelease,
  316. [SelectionClear] = selclear,
  317. [SelectionNotify] = selnotify,
  318. [SelectionRequest] = selrequest,
  319. };
  320. /* Globals */
  321. static DC dc;
  322. static XWindow xw;
  323. static Term term;
  324. static CSIEscape csiescseq;
  325. static STREscape strescseq;
  326. static int cmdfd;
  327. static pid_t pid;
  328. static Selection sel;
  329. static int iofd = -1;
  330. static char **opt_cmd = NULL;
  331. static char *opt_io = NULL;
  332. static char *opt_title = NULL;
  333. static char *opt_embed = NULL;
  334. static char *opt_class = NULL;
  335. void *
  336. xmalloc(size_t len) {
  337. void *p = malloc(len);
  338. if(!p)
  339. die("Out of memory\n");
  340. return p;
  341. }
  342. void *
  343. xrealloc(void *p, size_t len) {
  344. if((p = realloc(p, len)) == NULL)
  345. die("Out of memory\n");
  346. return p;
  347. }
  348. void *
  349. xcalloc(size_t nmemb, size_t size) {
  350. void *p = calloc(nmemb, size);
  351. if(!p)
  352. die("Out of memory\n");
  353. return p;
  354. }
  355. char *
  356. smstrcat(char *src, ...)
  357. {
  358. va_list fmtargs;
  359. char *ret, *p, *v;
  360. int len, slen, flen;
  361. len = slen = strlen(src);
  362. va_start(fmtargs, src);
  363. for(;;) {
  364. v = va_arg(fmtargs, char *);
  365. if(v == NULL)
  366. break;
  367. len += strlen(v);
  368. }
  369. va_end(fmtargs);
  370. p = ret = xmalloc(len+1);
  371. memmove(p, src, slen);
  372. p += slen;
  373. va_start(fmtargs, src);
  374. for(;;) {
  375. v = va_arg(fmtargs, char *);
  376. if(v == NULL)
  377. break;
  378. flen = strlen(v);
  379. memmove(p, v, flen);
  380. p += flen;
  381. }
  382. va_end(fmtargs);
  383. ret[len] = '\0';
  384. return ret;
  385. }
  386. int
  387. utf8decode(char *s, long *u) {
  388. uchar c;
  389. int i, n, rtn;
  390. rtn = 1;
  391. c = *s;
  392. if(~c & B7) { /* 0xxxxxxx */
  393. *u = c;
  394. return rtn;
  395. } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
  396. *u = c&(B4|B3|B2|B1|B0);
  397. n = 1;
  398. } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
  399. *u = c&(B3|B2|B1|B0);
  400. n = 2;
  401. } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
  402. *u = c & (B2|B1|B0);
  403. n = 3;
  404. } else
  405. goto invalid;
  406. for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
  407. c = *s;
  408. if((c & (B7|B6)) != B7) /* 10xxxxxx */
  409. goto invalid;
  410. *u <<= 6;
  411. *u |= c & (B5|B4|B3|B2|B1|B0);
  412. }
  413. if((n == 1 && *u < 0x80) ||
  414. (n == 2 && *u < 0x800) ||
  415. (n == 3 && *u < 0x10000) ||
  416. (*u >= 0xD800 && *u <= 0xDFFF))
  417. goto invalid;
  418. return rtn;
  419. invalid:
  420. *u = 0xFFFD;
  421. return rtn;
  422. }
  423. int
  424. utf8encode(long *u, char *s) {
  425. uchar *sp;
  426. ulong uc;
  427. int i, n;
  428. sp = (uchar*) s;
  429. uc = *u;
  430. if(uc < 0x80) {
  431. *sp = uc; /* 0xxxxxxx */
  432. return 1;
  433. } else if(*u < 0x800) {
  434. *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
  435. n = 1;
  436. } else if(uc < 0x10000) {
  437. *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
  438. n = 2;
  439. } else if(uc <= 0x10FFFF) {
  440. *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
  441. n = 3;
  442. } else {
  443. goto invalid;
  444. }
  445. for(i=n,++sp; i>0; --i,++sp)
  446. *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
  447. return n+1;
  448. invalid:
  449. /* U+FFFD */
  450. *s++ = '\xEF';
  451. *s++ = '\xBF';
  452. *s = '\xBD';
  453. return 3;
  454. }
  455. /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
  456. UTF-8 otherwise return 0 */
  457. int
  458. isfullutf8(char *s, int b) {
  459. uchar *c1, *c2, *c3;
  460. c1 = (uchar *) s;
  461. c2 = (uchar *) ++s;
  462. c3 = (uchar *) ++s;
  463. if(b < 1)
  464. return 0;
  465. else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
  466. return 0;
  467. else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
  468. ((b == 1) ||
  469. ((b == 2) && (*c2&(B7|B6)) == B7)))
  470. return 0;
  471. else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
  472. ((b == 1) ||
  473. ((b == 2) && (*c2&(B7|B6)) == B7) ||
  474. ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
  475. return 0;
  476. else
  477. return 1;
  478. }
  479. int
  480. utf8size(char *s) {
  481. uchar c = *s;
  482. if(~c&B7)
  483. return 1;
  484. else if((c&(B7|B6|B5)) == (B7|B6))
  485. return 2;
  486. else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
  487. return 3;
  488. else
  489. return 4;
  490. }
  491. void
  492. selinit(void) {
  493. memset(&sel.tclick1, 0, sizeof(sel.tclick1));
  494. memset(&sel.tclick2, 0, sizeof(sel.tclick2));
  495. sel.mode = 0;
  496. sel.bx = -1;
  497. sel.clip = NULL;
  498. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  499. if(sel.xtarget == None)
  500. sel.xtarget = XA_STRING;
  501. }
  502. static inline bool
  503. selected(int x, int y) {
  504. if(sel.ey == y && sel.by == y) {
  505. int bx = MIN(sel.bx, sel.ex);
  506. int ex = MAX(sel.bx, sel.ex);
  507. return BETWEEN(x, bx, ex);
  508. }
  509. return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
  510. || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
  511. }
  512. void
  513. getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
  514. if(b)
  515. *b = e->xbutton.button;
  516. *x = X2COL(e->xbutton.x);
  517. *y = Y2ROW(e->xbutton.y);
  518. sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
  519. sel.b.y = MIN(sel.by, sel.ey);
  520. sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
  521. sel.e.y = MAX(sel.by, sel.ey);
  522. }
  523. void
  524. mousereport(XEvent *e) {
  525. int x = X2COL(e->xbutton.x);
  526. int y = Y2ROW(e->xbutton.y);
  527. int button = e->xbutton.button;
  528. int state = e->xbutton.state;
  529. char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
  530. static int ob, ox, oy;
  531. /* from urxvt */
  532. if(e->xbutton.type == MotionNotify) {
  533. if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
  534. return;
  535. button = ob + 32;
  536. ox = x, oy = y;
  537. } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
  538. button = 3;
  539. } else {
  540. button -= Button1;
  541. if(button >= 3)
  542. button += 64 - 3;
  543. if(e->xbutton.type == ButtonPress) {
  544. ob = button;
  545. ox = x, oy = y;
  546. }
  547. }
  548. buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
  549. + (state & Mod4Mask ? 8 : 0)
  550. + (state & ControlMask ? 16 : 0);
  551. ttywrite(buf, sizeof(buf));
  552. }
  553. void
  554. bpress(XEvent *e) {
  555. if(IS_SET(MODE_MOUSE))
  556. mousereport(e);
  557. else if(e->xbutton.button == Button1) {
  558. if(sel.bx != -1) {
  559. sel.bx = -1;
  560. tsetdirt(sel.b.y, sel.e.y);
  561. draw();
  562. }
  563. sel.mode = 1;
  564. sel.ex = sel.bx = X2COL(e->xbutton.x);
  565. sel.ey = sel.by = Y2ROW(e->xbutton.y);
  566. }
  567. }
  568. void
  569. selcopy(void) {
  570. char *str, *ptr;
  571. int x, y, bufsize, is_selected = 0;
  572. if(sel.bx == -1)
  573. str = NULL;
  574. else {
  575. bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
  576. ptr = str = xmalloc(bufsize);
  577. /* append every set & selected glyph to the selection */
  578. for(y = 0; y < term.row; y++) {
  579. for(x = 0; x < term.col; x++) {
  580. int size;
  581. char *p;
  582. Glyph *gp = &term.line[y][x];
  583. if(!(is_selected = selected(x, y)))
  584. continue;
  585. p = (gp->state & GLYPH_SET) ? gp->c : " ";
  586. size = utf8size(p);
  587. memcpy(ptr, p, size);
  588. ptr += size;
  589. }
  590. /* \n at the end of every selected line except for the last one */
  591. if(is_selected && y < sel.e.y)
  592. *ptr++ = '\n';
  593. }
  594. *ptr = 0;
  595. }
  596. sel.alt = IS_SET(MODE_ALTSCREEN);
  597. xsetsel(str);
  598. }
  599. void
  600. selnotify(XEvent *e) {
  601. ulong nitems, ofs, rem;
  602. int format;
  603. uchar *data;
  604. Atom type;
  605. ofs = 0;
  606. do {
  607. if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
  608. False, AnyPropertyType, &type, &format,
  609. &nitems, &rem, &data)) {
  610. fprintf(stderr, "Clipboard allocation failed\n");
  611. return;
  612. }
  613. ttywrite((const char *) data, nitems * format / 8);
  614. XFree(data);
  615. /* number of 32-bit chunks returned */
  616. ofs += nitems * format / 32;
  617. } while(rem > 0);
  618. }
  619. void
  620. selpaste() {
  621. XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
  622. }
  623. void selclear(XEvent *e) {
  624. if(sel.bx == -1)
  625. return;
  626. sel.bx = -1;
  627. tsetdirt(sel.b.y, sel.e.y);
  628. }
  629. void
  630. selrequest(XEvent *e) {
  631. XSelectionRequestEvent *xsre;
  632. XSelectionEvent xev;
  633. Atom xa_targets;
  634. xsre = (XSelectionRequestEvent *) e;
  635. xev.type = SelectionNotify;
  636. xev.requestor = xsre->requestor;
  637. xev.selection = xsre->selection;
  638. xev.target = xsre->target;
  639. xev.time = xsre->time;
  640. /* reject */
  641. xev.property = None;
  642. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  643. if(xsre->target == xa_targets) {
  644. /* respond with the supported type */
  645. Atom string = sel.xtarget;
  646. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  647. XA_ATOM, 32, PropModeReplace,
  648. (uchar *) &string, 1);
  649. xev.property = xsre->property;
  650. } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
  651. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  652. xsre->target, 8, PropModeReplace,
  653. (uchar *) sel.clip, strlen(sel.clip));
  654. xev.property = xsre->property;
  655. }
  656. /* all done, send a notification to the listener */
  657. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  658. fprintf(stderr, "Error sending SelectionNotify event\n");
  659. }
  660. void
  661. xsetsel(char *str) {
  662. /* register the selection for both the clipboard and the primary */
  663. Atom clipboard;
  664. free(sel.clip);
  665. sel.clip = str;
  666. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
  667. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  668. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  669. }
  670. void
  671. brelease(XEvent *e) {
  672. if(IS_SET(MODE_MOUSE)) {
  673. mousereport(e);
  674. return;
  675. }
  676. if(e->xbutton.button == Button2)
  677. selpaste();
  678. else if(e->xbutton.button == Button1) {
  679. sel.mode = 0;
  680. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  681. term.dirty[sel.ey] = 1;
  682. if(sel.bx == sel.ex && sel.by == sel.ey) {
  683. struct timeval now;
  684. sel.bx = -1;
  685. gettimeofday(&now, NULL);
  686. if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
  687. /* triple click on the line */
  688. sel.b.x = sel.bx = 0;
  689. sel.e.x = sel.ex = term.col;
  690. sel.b.y = sel.e.y = sel.ey;
  691. selcopy();
  692. } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
  693. /* double click to select word */
  694. sel.bx = sel.ex;
  695. while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
  696. term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
  697. sel.b.x = sel.bx;
  698. while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
  699. term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
  700. sel.e.x = sel.ex;
  701. sel.b.y = sel.e.y = sel.ey;
  702. selcopy();
  703. }
  704. } else
  705. selcopy();
  706. }
  707. memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
  708. gettimeofday(&sel.tclick1, NULL);
  709. }
  710. void
  711. bmotion(XEvent *e) {
  712. if(IS_SET(MODE_MOUSE)) {
  713. mousereport(e);
  714. return;
  715. }
  716. if(sel.mode) {
  717. int oldey = sel.ey, oldex = sel.ex;
  718. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  719. if(oldey != sel.ey || oldex != sel.ex) {
  720. int starty = MIN(oldey, sel.ey);
  721. int endy = MAX(oldey, sel.ey);
  722. tsetdirt(starty, endy);
  723. }
  724. }
  725. }
  726. void
  727. die(const char *errstr, ...) {
  728. va_list ap;
  729. va_start(ap, errstr);
  730. vfprintf(stderr, errstr, ap);
  731. va_end(ap);
  732. exit(EXIT_FAILURE);
  733. }
  734. void
  735. execsh(void) {
  736. char **args;
  737. char *envshell = getenv("SHELL");
  738. unsetenv("COLUMNS");
  739. unsetenv("LINES");
  740. unsetenv("TERMCAP");
  741. signal(SIGCHLD, SIG_DFL);
  742. signal(SIGHUP, SIG_DFL);
  743. signal(SIGINT, SIG_DFL);
  744. signal(SIGQUIT, SIG_DFL);
  745. signal(SIGTERM, SIG_DFL);
  746. signal(SIGALRM, SIG_DFL);
  747. DEFAULT(envshell, SHELL);
  748. putenv("TERM="TNAME);
  749. args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
  750. execvp(args[0], args);
  751. exit(EXIT_FAILURE);
  752. }
  753. void
  754. sigchld(int a) {
  755. int stat = 0;
  756. if(waitpid(pid, &stat, 0) < 0)
  757. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  758. if(WIFEXITED(stat))
  759. exit(WEXITSTATUS(stat));
  760. else
  761. exit(EXIT_FAILURE);
  762. }
  763. void
  764. ttynew(void) {
  765. int m, s;
  766. /* seems to work fine on linux, openbsd and freebsd */
  767. struct winsize w = {term.row, term.col, 0, 0};
  768. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  769. die("openpty failed: %s\n", SERRNO);
  770. switch(pid = fork()) {
  771. case -1:
  772. die("fork failed\n");
  773. break;
  774. case 0:
  775. setsid(); /* create a new process group */
  776. dup2(s, STDIN_FILENO);
  777. dup2(s, STDOUT_FILENO);
  778. dup2(s, STDERR_FILENO);
  779. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  780. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  781. close(s);
  782. close(m);
  783. execsh();
  784. break;
  785. default:
  786. close(s);
  787. cmdfd = m;
  788. signal(SIGCHLD, sigchld);
  789. if(opt_io) {
  790. if(!strcmp(opt_io, "-")) {
  791. iofd = STDOUT_FILENO;
  792. } else {
  793. if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
  794. fprintf(stderr, "Error opening %s:%s\n",
  795. opt_io, strerror(errno));
  796. }
  797. }
  798. }
  799. }
  800. }
  801. void
  802. dump(char c) {
  803. static int col;
  804. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  805. if(++col % 10 == 0)
  806. fprintf(stderr, "\n");
  807. }
  808. void
  809. ttyread(void) {
  810. static char buf[BUFSIZ];
  811. static int buflen = 0;
  812. char *ptr;
  813. char s[UTF_SIZ];
  814. int charsize; /* size of utf8 char in bytes */
  815. long utf8c;
  816. int ret;
  817. /* append read bytes to unprocessed bytes */
  818. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  819. die("Couldn't read from shell: %s\n", SERRNO);
  820. /* process every complete utf8 char */
  821. buflen += ret;
  822. ptr = buf;
  823. while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
  824. charsize = utf8decode(ptr, &utf8c);
  825. utf8encode(&utf8c, s);
  826. tputc(s, charsize);
  827. ptr += charsize;
  828. buflen -= charsize;
  829. }
  830. /* keep any uncomplete utf8 char for the next call */
  831. memmove(buf, ptr, buflen);
  832. }
  833. void
  834. ttywrite(const char *s, size_t n) {
  835. if(write(cmdfd, s, n) == -1)
  836. die("write error on tty: %s\n", SERRNO);
  837. }
  838. void
  839. ttyresize(void) {
  840. struct winsize w;
  841. w.ws_row = term.row;
  842. w.ws_col = term.col;
  843. w.ws_xpixel = xw.tw;
  844. w.ws_ypixel = xw.th;
  845. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  846. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  847. }
  848. void
  849. tsetdirt(int top, int bot)
  850. {
  851. int i;
  852. LIMIT(top, 0, term.row-1);
  853. LIMIT(bot, 0, term.row-1);
  854. for(i = top; i <= bot; i++)
  855. term.dirty[i] = 1;
  856. }
  857. void
  858. tfulldirt(void)
  859. {
  860. tsetdirt(0, term.row-1);
  861. }
  862. void
  863. tcursor(int mode) {
  864. static TCursor c;
  865. if(mode == CURSOR_SAVE)
  866. c = term.c;
  867. else if(mode == CURSOR_LOAD)
  868. term.c = c, tmoveto(c.x, c.y);
  869. }
  870. void
  871. treset(void) {
  872. uint i;
  873. term.c = (TCursor){{
  874. .mode = ATTR_NULL,
  875. .fg = DefaultFG,
  876. .bg = DefaultBG
  877. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  878. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  879. for(i = TAB; i < term.col; i += TAB)
  880. term.tabs[i] = 1;
  881. term.top = 0, term.bot = term.row - 1;
  882. term.mode = MODE_WRAP;
  883. tclearregion(0, 0, term.col-1, term.row-1);
  884. }
  885. void
  886. tnew(int col, int row) {
  887. /* set screen size */
  888. term.row = row, term.col = col;
  889. term.line = xmalloc(term.row * sizeof(Line));
  890. term.alt = xmalloc(term.row * sizeof(Line));
  891. term.dirty = xmalloc(term.row * sizeof(*term.dirty));
  892. term.tabs = xmalloc(term.col * sizeof(*term.tabs));
  893. for(row = 0; row < term.row; row++) {
  894. term.line[row] = xmalloc(term.col * sizeof(Glyph));
  895. term.alt [row] = xmalloc(term.col * sizeof(Glyph));
  896. term.dirty[row] = 0;
  897. }
  898. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  899. /* setup screen */
  900. treset();
  901. }
  902. void
  903. tswapscreen(void) {
  904. Line* tmp = term.line;
  905. term.line = term.alt;
  906. term.alt = tmp;
  907. term.mode ^= MODE_ALTSCREEN;
  908. tfulldirt();
  909. }
  910. void
  911. tscrolldown(int orig, int n) {
  912. int i;
  913. Line temp;
  914. LIMIT(n, 0, term.bot-orig+1);
  915. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  916. for(i = term.bot; i >= orig+n; i--) {
  917. temp = term.line[i];
  918. term.line[i] = term.line[i-n];
  919. term.line[i-n] = temp;
  920. term.dirty[i] = 1;
  921. term.dirty[i-n] = 1;
  922. }
  923. selscroll(orig, n);
  924. }
  925. void
  926. tscrollup(int orig, int n) {
  927. int i;
  928. Line temp;
  929. LIMIT(n, 0, term.bot-orig+1);
  930. tclearregion(0, orig, term.col-1, orig+n-1);
  931. for(i = orig; i <= term.bot-n; i++) {
  932. temp = term.line[i];
  933. term.line[i] = term.line[i+n];
  934. term.line[i+n] = temp;
  935. term.dirty[i] = 1;
  936. term.dirty[i+n] = 1;
  937. }
  938. selscroll(orig, -n);
  939. }
  940. void
  941. selscroll(int orig, int n) {
  942. if(sel.bx == -1)
  943. return;
  944. if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
  945. if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
  946. sel.bx = -1;
  947. return;
  948. }
  949. if(sel.by < term.top) {
  950. sel.by = term.top;
  951. sel.bx = 0;
  952. }
  953. if(sel.ey > term.bot) {
  954. sel.ey = term.bot;
  955. sel.ex = term.col;
  956. }
  957. sel.b.y = sel.by, sel.b.x = sel.bx;
  958. sel.e.y = sel.ey, sel.e.x = sel.ex;
  959. }
  960. }
  961. void
  962. tnewline(int first_col) {
  963. int y = term.c.y;
  964. if(y == term.bot)
  965. tscrollup(term.top, 1);
  966. else
  967. y++;
  968. tmoveto(first_col ? 0 : term.c.x, y);
  969. }
  970. void
  971. csiparse(void) {
  972. /* int noarg = 1; */
  973. char *p = csiescseq.buf;
  974. csiescseq.narg = 0;
  975. if(*p == '?')
  976. csiescseq.priv = 1, p++;
  977. while(p < csiescseq.buf+csiescseq.len) {
  978. while(isdigit(*p)) {
  979. csiescseq.arg[csiescseq.narg] *= 10;
  980. csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
  981. }
  982. if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
  983. csiescseq.narg++, p++;
  984. else {
  985. csiescseq.mode = *p;
  986. csiescseq.narg++;
  987. return;
  988. }
  989. }
  990. }
  991. void
  992. tmoveto(int x, int y) {
  993. LIMIT(x, 0, term.col-1);
  994. LIMIT(y, 0, term.row-1);
  995. term.c.state &= ~CURSOR_WRAPNEXT;
  996. term.c.x = x;
  997. term.c.y = y;
  998. }
  999. void
  1000. tsetchar(char *c) {
  1001. /*
  1002. * The table is proudly stolen from rxvt.
  1003. */
  1004. if(term.c.attr.mode & ATTR_GFX) {
  1005. char *vt100_0[62] = { /* 0x41 - 0x7e */
  1006. "", "", "", "", "", "", "", /* A - G */
  1007. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  1008. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  1009. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  1010. "", "", "", "", "", "", "°", "±", /* ` - g */
  1011. "", "", "", "", "", "", "", "", /* h - o */
  1012. "", "", "", "", "", "", "", "", /* p - w */
  1013. "", "", "", "π", "", "£", "·", /* x - ~ */
  1014. };
  1015. if(c[0] >= 0x41 && c[0] <= 0x7e
  1016. && vt100_0[c[0] - 0x41]) {
  1017. c = vt100_0[c[0] - 0x41];
  1018. }
  1019. }
  1020. term.dirty[term.c.y] = 1;
  1021. term.line[term.c.y][term.c.x] = term.c.attr;
  1022. memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
  1023. term.line[term.c.y][term.c.x].state |= GLYPH_SET;
  1024. }
  1025. void
  1026. tclearregion(int x1, int y1, int x2, int y2) {
  1027. int x, y, temp;
  1028. if(x1 > x2)
  1029. temp = x1, x1 = x2, x2 = temp;
  1030. if(y1 > y2)
  1031. temp = y1, y1 = y2, y2 = temp;
  1032. LIMIT(x1, 0, term.col-1);
  1033. LIMIT(x2, 0, term.col-1);
  1034. LIMIT(y1, 0, term.row-1);
  1035. LIMIT(y2, 0, term.row-1);
  1036. for(y = y1; y <= y2; y++) {
  1037. term.dirty[y] = 1;
  1038. for(x = x1; x <= x2; x++)
  1039. term.line[y][x].state = 0;
  1040. }
  1041. }
  1042. void
  1043. tdeletechar(int n) {
  1044. int src = term.c.x + n;
  1045. int dst = term.c.x;
  1046. int size = term.col - src;
  1047. term.dirty[term.c.y] = 1;
  1048. if(src >= term.col) {
  1049. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1050. return;
  1051. }
  1052. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  1053. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1054. }
  1055. void
  1056. tinsertblank(int n) {
  1057. int src = term.c.x;
  1058. int dst = src + n;
  1059. int size = term.col - dst;
  1060. term.dirty[term.c.y] = 1;
  1061. if(dst >= term.col) {
  1062. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1063. return;
  1064. }
  1065. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  1066. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1067. }
  1068. void
  1069. tinsertblankline(int n) {
  1070. if(term.c.y < term.top || term.c.y > term.bot)
  1071. return;
  1072. tscrolldown(term.c.y, n);
  1073. }
  1074. void
  1075. tdeleteline(int n) {
  1076. if(term.c.y < term.top || term.c.y > term.bot)
  1077. return;
  1078. tscrollup(term.c.y, n);
  1079. }
  1080. void
  1081. tsetattr(int *attr, int l) {
  1082. int i;
  1083. for(i = 0; i < l; i++) {
  1084. switch(attr[i]) {
  1085. case 0:
  1086. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
  1087. | ATTR_ITALIC | ATTR_BLINK);
  1088. term.c.attr.fg = DefaultFG;
  1089. term.c.attr.bg = DefaultBG;
  1090. break;
  1091. case 1:
  1092. term.c.attr.mode |= ATTR_BOLD;
  1093. break;
  1094. case 3: /* enter standout (highlight) */
  1095. term.c.attr.mode |= ATTR_ITALIC;
  1096. break;
  1097. case 4:
  1098. term.c.attr.mode |= ATTR_UNDERLINE;
  1099. break;
  1100. case 5:
  1101. term.c.attr.mode |= ATTR_BLINK;
  1102. break;
  1103. case 7:
  1104. term.c.attr.mode |= ATTR_REVERSE;
  1105. break;
  1106. case 21:
  1107. case 22:
  1108. term.c.attr.mode &= ~ATTR_BOLD;
  1109. break;
  1110. case 23: /* leave standout (highlight) mode */
  1111. term.c.attr.mode &= ~ATTR_ITALIC;
  1112. break;
  1113. case 24:
  1114. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1115. break;
  1116. case 25:
  1117. term.c.attr.mode &= ~ATTR_BLINK;
  1118. break;
  1119. case 27:
  1120. term.c.attr.mode &= ~ATTR_REVERSE;
  1121. break;
  1122. case 38:
  1123. if(i + 2 < l && attr[i + 1] == 5) {
  1124. i += 2;
  1125. if(BETWEEN(attr[i], 0, 255))
  1126. term.c.attr.fg = attr[i];
  1127. else
  1128. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
  1129. }
  1130. else
  1131. fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
  1132. break;
  1133. case 39:
  1134. term.c.attr.fg = DefaultFG;
  1135. break;
  1136. case 48:
  1137. if(i + 2 < l && attr[i + 1] == 5) {
  1138. i += 2;
  1139. if(BETWEEN(attr[i], 0, 255))
  1140. term.c.attr.bg = attr[i];
  1141. else
  1142. fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
  1143. }
  1144. else
  1145. fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
  1146. break;
  1147. case 49:
  1148. term.c.attr.bg = DefaultBG;
  1149. break;
  1150. default:
  1151. if(BETWEEN(attr[i], 30, 37))
  1152. term.c.attr.fg = attr[i] - 30;
  1153. else if(BETWEEN(attr[i], 40, 47))
  1154. term.c.attr.bg = attr[i] - 40;
  1155. else if(BETWEEN(attr[i], 90, 97))
  1156. term.c.attr.fg = attr[i] - 90 + 8;
  1157. else if(BETWEEN(attr[i], 100, 107))
  1158. term.c.attr.bg = attr[i] - 100 + 8;
  1159. else
  1160. fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
  1161. break;
  1162. }
  1163. }
  1164. }
  1165. void
  1166. tsetscroll(int t, int b) {
  1167. int temp;
  1168. LIMIT(t, 0, term.row-1);
  1169. LIMIT(b, 0, term.row-1);
  1170. if(t > b) {
  1171. temp = t;
  1172. t = b;
  1173. b = temp;
  1174. }
  1175. term.top = t;
  1176. term.bot = b;
  1177. }
  1178. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1179. void
  1180. tsetmode(bool priv, bool set, int *args, int narg) {
  1181. int *lim, mode;
  1182. for(lim = args + narg; args < lim; ++args) {
  1183. if(priv) {
  1184. switch(*args) {
  1185. break;
  1186. case 1: /* DECCKM -- Cursor key */
  1187. MODBIT(term.mode, set, MODE_APPKEYPAD);
  1188. break;
  1189. case 5: /* DECSCNM -- Reverve video */
  1190. mode = term.mode;
  1191. MODBIT(term.mode, set, MODE_REVERSE);
  1192. if(mode != term.mode)
  1193. redraw();
  1194. break;
  1195. case 6: /* XXX: DECOM -- Origin */
  1196. break;
  1197. case 7: /* DECAWM -- Auto wrap */
  1198. MODBIT(term.mode, set, MODE_WRAP);
  1199. break;
  1200. case 8: /* XXX: DECARM -- Auto repeat */
  1201. break;
  1202. case 0: /* Error (IGNORED) */
  1203. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1204. break;
  1205. case 25:
  1206. MODBIT(term.c.state, !set, CURSOR_HIDE);
  1207. break;
  1208. case 1000: /* 1000,1002: enable xterm mouse report */
  1209. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1210. break;
  1211. case 1002:
  1212. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1213. break;
  1214. case 1049: /* = 1047 and 1048 */
  1215. case 47:
  1216. case 1047:
  1217. if(IS_SET(MODE_ALTSCREEN))
  1218. tclearregion(0, 0, term.col-1, term.row-1);
  1219. if((set && !IS_SET(MODE_ALTSCREEN)) ||
  1220. (!set && IS_SET(MODE_ALTSCREEN))) {
  1221. tswapscreen();
  1222. }
  1223. if(*args != 1049)
  1224. break;
  1225. /* pass through */
  1226. case 1048:
  1227. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1228. break;
  1229. default:
  1230. /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
  1231. /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
  1232. /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
  1233. /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
  1234. /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
  1235. /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
  1236. fprintf(stderr,
  1237. "erresc: unknown private set/reset mode %d\n",
  1238. *args);
  1239. break;
  1240. }
  1241. } else {
  1242. switch(*args) {
  1243. case 0: /* Error (IGNORED) */
  1244. break;
  1245. case 2: /* KAM -- keyboard action */
  1246. MODBIT(term.mode, set, MODE_KBDLOCK);
  1247. break;
  1248. case 4: /* IRM -- Insertion-replacement */
  1249. MODBIT(term.mode, set, MODE_INSERT);
  1250. break;
  1251. case 12: /* XXX: SRM -- Send/Receive */
  1252. break;
  1253. case 20: /* LNM -- Linefeed/new line */
  1254. MODBIT(term.mode, set, MODE_CRLF);
  1255. break;
  1256. default:
  1257. fprintf(stderr,
  1258. "erresc: unknown set/reset mode %d\n",
  1259. *args);
  1260. break;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. #undef MODBIT
  1266. void
  1267. csihandle(void) {
  1268. switch(csiescseq.mode) {
  1269. default:
  1270. unknown:
  1271. fprintf(stderr, "erresc: unknown csi ");
  1272. csidump();
  1273. /* die(""); */
  1274. break;
  1275. case '@': /* ICH -- Insert <n> blank char */
  1276. DEFAULT(csiescseq.arg[0], 1);
  1277. tinsertblank(csiescseq.arg[0]);
  1278. break;
  1279. case 'A': /* CUU -- Cursor <n> Up */
  1280. case 'e':
  1281. DEFAULT(csiescseq.arg[0], 1);
  1282. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1283. break;
  1284. case 'B': /* CUD -- Cursor <n> Down */
  1285. DEFAULT(csiescseq.arg[0], 1);
  1286. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1287. break;
  1288. case 'C': /* CUF -- Cursor <n> Forward */
  1289. case 'a':
  1290. DEFAULT(csiescseq.arg[0], 1);
  1291. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1292. break;
  1293. case 'D': /* CUB -- Cursor <n> Backward */
  1294. DEFAULT(csiescseq.arg[0], 1);
  1295. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1296. break;
  1297. case 'E': /* CNL -- Cursor <n> Down and first col */
  1298. DEFAULT(csiescseq.arg[0], 1);
  1299. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1300. break;
  1301. case 'F': /* CPL -- Cursor <n> Up and first col */
  1302. DEFAULT(csiescseq.arg[0], 1);
  1303. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1304. break;
  1305. case 'g': /* TBC -- Tabulation clear */
  1306. switch (csiescseq.arg[0]) {
  1307. case 0: /* clear current tab stop */
  1308. term.tabs[term.c.x] = 0;
  1309. break;
  1310. case 3: /* clear all the tabs */
  1311. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1312. break;
  1313. default:
  1314. goto unknown;
  1315. }
  1316. break;
  1317. case 'G': /* CHA -- Move to <col> */
  1318. case '`': /* HPA */
  1319. DEFAULT(csiescseq.arg[0], 1);
  1320. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1321. break;
  1322. case 'H': /* CUP -- Move to <row> <col> */
  1323. case 'f': /* HVP */
  1324. DEFAULT(csiescseq.arg[0], 1);
  1325. DEFAULT(csiescseq.arg[1], 1);
  1326. tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1327. break;
  1328. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1329. DEFAULT(csiescseq.arg[0], 1);
  1330. while(csiescseq.arg[0]--)
  1331. tputtab(1);
  1332. break;
  1333. case 'J': /* ED -- Clear screen */
  1334. sel.bx = -1;
  1335. switch(csiescseq.arg[0]) {
  1336. case 0: /* below */
  1337. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1338. if(term.c.y < term.row-1)
  1339. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  1340. break;
  1341. case 1: /* above */
  1342. if(term.c.y > 1)
  1343. tclearregion(0, 0, term.col-1, term.c.y-1);
  1344. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1345. break;
  1346. case 2: /* all */
  1347. tclearregion(0, 0, term.col-1, term.row-1);
  1348. break;
  1349. default:
  1350. goto unknown;
  1351. }
  1352. break;
  1353. case 'K': /* EL -- Clear line */
  1354. switch(csiescseq.arg[0]) {
  1355. case 0: /* right */
  1356. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1357. break;
  1358. case 1: /* left */
  1359. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1360. break;
  1361. case 2: /* all */
  1362. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1363. break;
  1364. }
  1365. break;
  1366. case 'S': /* SU -- Scroll <n> line up */
  1367. DEFAULT(csiescseq.arg[0], 1);
  1368. tscrollup(term.top, csiescseq.arg[0]);
  1369. break;
  1370. case 'T': /* SD -- Scroll <n> line down */
  1371. DEFAULT(csiescseq.arg[0], 1);
  1372. tscrolldown(term.top, csiescseq.arg[0]);
  1373. break;
  1374. case 'L': /* IL -- Insert <n> blank lines */
  1375. DEFAULT(csiescseq.arg[0], 1);
  1376. tinsertblankline(csiescseq.arg[0]);
  1377. break;
  1378. case 'l': /* RM -- Reset Mode */
  1379. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1380. break;
  1381. case 'M': /* DL -- Delete <n> lines */
  1382. DEFAULT(csiescseq.arg[0], 1);
  1383. tdeleteline(csiescseq.arg[0]);
  1384. break;
  1385. case 'X': /* ECH -- Erase <n> char */
  1386. DEFAULT(csiescseq.arg[0], 1);
  1387. tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
  1388. break;
  1389. case 'P': /* DCH -- Delete <n> char */
  1390. DEFAULT(csiescseq.arg[0], 1);
  1391. tdeletechar(csiescseq.arg[0]);
  1392. break;
  1393. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1394. DEFAULT(csiescseq.arg[0], 1);
  1395. while(csiescseq.arg[0]--)
  1396. tputtab(0);
  1397. break;
  1398. case 'd': /* VPA -- Move to <row> */
  1399. DEFAULT(csiescseq.arg[0], 1);
  1400. tmoveto(term.c.x, csiescseq.arg[0]-1);
  1401. break;
  1402. case 'h': /* SM -- Set terminal mode */
  1403. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1404. break;
  1405. case 'm': /* SGR -- Terminal attribute (color) */
  1406. tsetattr(csiescseq.arg, csiescseq.narg);
  1407. break;
  1408. case 'r': /* DECSTBM -- Set Scrolling Region */
  1409. if(csiescseq.priv)
  1410. goto unknown;
  1411. else {
  1412. DEFAULT(csiescseq.arg[0], 1);
  1413. DEFAULT(csiescseq.arg[1], term.row);
  1414. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1415. tmoveto(0, 0);
  1416. }
  1417. break;
  1418. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1419. tcursor(CURSOR_SAVE);
  1420. break;
  1421. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1422. tcursor(CURSOR_LOAD);
  1423. break;
  1424. }
  1425. }
  1426. void
  1427. csidump(void) {
  1428. int i;
  1429. printf("ESC[");
  1430. for(i = 0; i < csiescseq.len; i++) {
  1431. uint c = csiescseq.buf[i] & 0xff;
  1432. if(isprint(c)) putchar(c);
  1433. else if(c == '\n') printf("(\\n)");
  1434. else if(c == '\r') printf("(\\r)");
  1435. else if(c == 0x1b) printf("(\\e)");
  1436. else printf("(%02x)", c);
  1437. }
  1438. putchar('\n');
  1439. }
  1440. void
  1441. csireset(void) {
  1442. memset(&csiescseq, 0, sizeof(csiescseq));
  1443. }
  1444. void
  1445. strhandle(void) {
  1446. char *p;
  1447. /*
  1448. * TODO: make this being useful in case of color palette change.
  1449. */
  1450. strparse();
  1451. p = strescseq.buf;
  1452. switch(strescseq.type) {
  1453. case ']': /* OSC -- Operating System Command */
  1454. switch(p[0]) {
  1455. case '0':
  1456. case '1':
  1457. case '2':
  1458. /*
  1459. * TODO: Handle special chars in string, like umlauts.
  1460. */
  1461. if(p[1] == ';') {
  1462. XStoreName(xw.dpy, xw.win, strescseq.buf+2);
  1463. }
  1464. break;
  1465. case ';':
  1466. XStoreName(xw.dpy, xw.win, strescseq.buf+1);
  1467. break;
  1468. case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
  1469. break;
  1470. default:
  1471. fprintf(stderr, "erresc: unknown str ");
  1472. strdump();
  1473. break;
  1474. }
  1475. break;
  1476. case 'k': /* old title set compatibility */
  1477. XStoreName(xw.dpy, xw.win, strescseq.buf);
  1478. break;
  1479. case 'P': /* DSC -- Device Control String */
  1480. case '_': /* APC -- Application Program Command */
  1481. case '^': /* PM -- Privacy Message */
  1482. default:
  1483. fprintf(stderr, "erresc: unknown str ");
  1484. strdump();
  1485. /* die(""); */
  1486. break;
  1487. }
  1488. }
  1489. void
  1490. strparse(void) {
  1491. /*
  1492. * TODO: Implement parsing like for CSI when required.
  1493. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1494. */
  1495. return;
  1496. }
  1497. void
  1498. strdump(void) {
  1499. int i;
  1500. printf("ESC%c", strescseq.type);
  1501. for(i = 0; i < strescseq.len; i++) {
  1502. uint c = strescseq.buf[i] & 0xff;
  1503. if(isprint(c)) putchar(c);
  1504. else if(c == '\n') printf("(\\n)");
  1505. else if(c == '\r') printf("(\\r)");
  1506. else if(c == 0x1b) printf("(\\e)");
  1507. else printf("(%02x)", c);
  1508. }
  1509. printf("ESC\\\n");
  1510. }
  1511. void
  1512. strreset(void) {
  1513. memset(&strescseq, 0, sizeof(strescseq));
  1514. }
  1515. void
  1516. tputtab(bool forward) {
  1517. uint x = term.c.x;
  1518. if(forward) {
  1519. if(x == term.col)
  1520. return;
  1521. for(++x; x < term.col && !term.tabs[x]; ++x)
  1522. /* nothing */ ;
  1523. } else {
  1524. if(x == 0)
  1525. return;
  1526. for(--x; x > 0 && !term.tabs[x]; --x)
  1527. /* nothing */ ;
  1528. }
  1529. tmoveto(x, term.c.y);
  1530. }
  1531. void
  1532. tputc(char *c, int len) {
  1533. uchar ascii = *c;
  1534. if(iofd != -1)
  1535. write(iofd, c, len);
  1536. switch(ascii) {
  1537. case '\t':
  1538. tputtab(1);
  1539. return;
  1540. case '\b':
  1541. tmoveto(term.c.x-1, term.c.y);
  1542. return;
  1543. case '\r':
  1544. tmoveto(0, term.c.y);
  1545. return;
  1546. case '\f':
  1547. case '\v':
  1548. case '\n':
  1549. /* go to first col if the mode is set */
  1550. tnewline(IS_SET(MODE_CRLF));
  1551. return;
  1552. case '\a':
  1553. if(term.esc & ESC_STR)
  1554. break;
  1555. if(!(xw.state & WIN_FOCUSED))
  1556. xseturgency(1);
  1557. return;
  1558. case '\033':
  1559. csireset();
  1560. term.esc = ESC_START;
  1561. return;
  1562. }
  1563. if(term.esc & ESC_START) {
  1564. if(term.esc & ESC_CSI) {
  1565. csiescseq.buf[csiescseq.len++] = ascii;
  1566. if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
  1567. term.esc = 0;
  1568. csiparse(), csihandle();
  1569. }
  1570. } else if(term.esc & ESC_STR) {
  1571. switch(ascii) {
  1572. case '\033':
  1573. term.esc = ESC_START | ESC_STR_END;
  1574. break;
  1575. case '\a': /* backwards compatibility to xterm */
  1576. term.esc = 0;
  1577. strhandle();
  1578. break;
  1579. default:
  1580. strescseq.buf[strescseq.len++] = ascii;
  1581. if(strescseq.len+1 >= STR_BUF_SIZ) {
  1582. term.esc = 0;
  1583. strhandle();
  1584. }
  1585. }
  1586. } else if(term.esc & ESC_STR_END) {
  1587. term.esc = 0;
  1588. if(ascii == '\\')
  1589. strhandle();
  1590. } else if(term.esc & ESC_ALTCHARSET) {
  1591. switch(ascii) {
  1592. case '0': /* Line drawing set */
  1593. term.c.attr.mode |= ATTR_GFX;
  1594. break;
  1595. case 'B': /* USASCII */
  1596. term.c.attr.mode &= ~ATTR_GFX;
  1597. break;
  1598. case 'A': /* UK (IGNORED) */
  1599. case '<': /* multinational charset (IGNORED) */
  1600. case '5': /* Finnish (IGNORED) */
  1601. case 'C': /* Finnish (IGNORED) */
  1602. case 'K': /* German (IGNORED) */
  1603. break;
  1604. default:
  1605. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1606. }
  1607. term.esc = 0;
  1608. } else {
  1609. switch(ascii) {
  1610. case '[':
  1611. term.esc |= ESC_CSI;
  1612. break;
  1613. case 'P': /* DCS -- Device Control String */
  1614. case '_': /* APC -- Application Program Command */
  1615. case '^': /* PM -- Privacy Message */
  1616. case ']': /* OSC -- Operating System Command */
  1617. case 'k': /* old title set compatibility */
  1618. strreset();
  1619. strescseq.type = ascii;
  1620. term.esc |= ESC_STR;
  1621. break;
  1622. case '(': /* set primary charset G0 */
  1623. term.esc |= ESC_ALTCHARSET;
  1624. break;
  1625. case ')': /* set secondary charset G1 (IGNORED) */
  1626. case '*': /* set tertiary charset G2 (IGNORED) */
  1627. case '+': /* set quaternary charset G3 (IGNORED) */
  1628. term.esc = 0;
  1629. break;
  1630. case 'D': /* IND -- Linefeed */
  1631. if(term.c.y == term.bot)
  1632. tscrollup(term.top, 1);
  1633. else
  1634. tmoveto(term.c.x, term.c.y+1);
  1635. term.esc = 0;
  1636. break;
  1637. case 'E': /* NEL -- Next line */
  1638. tnewline(1); /* always go to first col */
  1639. term.esc = 0;
  1640. break;
  1641. case 'H': /* HTS -- Horizontal tab stop */
  1642. term.tabs[term.c.x] = 1;
  1643. term.esc = 0;
  1644. break;
  1645. case 'M': /* RI -- Reverse index */
  1646. if(term.c.y == term.top)
  1647. tscrolldown(term.top, 1);
  1648. else
  1649. tmoveto(term.c.x, term.c.y-1);
  1650. term.esc = 0;
  1651. break;
  1652. case 'c': /* RIS -- Reset to inital state */
  1653. treset();
  1654. term.esc = 0;
  1655. xclearborders();
  1656. xresettitle();
  1657. break;
  1658. case '=': /* DECPAM -- Application keypad */
  1659. term.mode |= MODE_APPKEYPAD;
  1660. term.esc = 0;
  1661. break;
  1662. case '>': /* DECPNM -- Normal keypad */
  1663. term.mode &= ~MODE_APPKEYPAD;
  1664. term.esc = 0;
  1665. break;
  1666. case '7': /* DECSC -- Save Cursor */
  1667. tcursor(CURSOR_SAVE);
  1668. term.esc = 0;
  1669. break;
  1670. case '8': /* DECRC -- Restore Cursor */
  1671. tcursor(CURSOR_LOAD);
  1672. term.esc = 0;
  1673. break;
  1674. case '\\': /* ST -- Stop */
  1675. term.esc = 0;
  1676. break;
  1677. default:
  1678. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1679. (uchar) ascii, isprint(ascii)?ascii:'.');
  1680. term.esc = 0;
  1681. }
  1682. }
  1683. } else {
  1684. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1685. sel.bx = -1;
  1686. if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
  1687. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1688. tnewline(1); /* always go to first col */
  1689. tsetchar(c);
  1690. if(term.c.x+1 < term.col)
  1691. tmoveto(term.c.x+1, term.c.y);
  1692. else
  1693. term.c.state |= CURSOR_WRAPNEXT;
  1694. }
  1695. }
  1696. }
  1697. int
  1698. tresize(int col, int row) {
  1699. int i, x;
  1700. int minrow = MIN(row, term.row);
  1701. int mincol = MIN(col, term.col);
  1702. int slide = term.c.y - row + 1;
  1703. if(col < 1 || row < 1)
  1704. return 0;
  1705. /* free unneeded rows */
  1706. i = 0;
  1707. if(slide > 0) {
  1708. /* slide screen to keep cursor where we expect it -
  1709. * tscrollup would work here, but we can optimize to
  1710. * memmove because we're freeing the earlier lines */
  1711. for(/* i = 0 */; i < slide; i++) {
  1712. free(term.line[i]);
  1713. free(term.alt[i]);
  1714. }
  1715. memmove(term.line, term.line + slide, row * sizeof(Line));
  1716. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1717. }
  1718. for(i += row; i < term.row; i++) {
  1719. free(term.line[i]);
  1720. free(term.alt[i]);
  1721. }
  1722. /* resize to new height */
  1723. term.line = xrealloc(term.line, row * sizeof(Line));
  1724. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1725. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1726. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1727. /* resize each row to new width, zero-pad if needed */
  1728. for(i = 0; i < minrow; i++) {
  1729. term.dirty[i] = 1;
  1730. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1731. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1732. for(x = mincol; x < col; x++) {
  1733. term.line[i][x].state = 0;
  1734. term.alt[i][x].state = 0;
  1735. }
  1736. }
  1737. /* allocate any new rows */
  1738. for(/* i == minrow */; i < row; i++) {
  1739. term.dirty[i] = 1;
  1740. term.line[i] = xcalloc(col, sizeof(Glyph));
  1741. term.alt [i] = xcalloc(col, sizeof(Glyph));
  1742. }
  1743. if(col > term.col) {
  1744. bool *bp = term.tabs + term.col;
  1745. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1746. while(--bp > term.tabs && !*bp)
  1747. /* nothing */ ;
  1748. for(bp += TAB; bp < term.tabs + col; bp += TAB)
  1749. *bp = 1;
  1750. }
  1751. /* update terminal size */
  1752. term.col = col, term.row = row;
  1753. /* make use of the LIMIT in tmoveto */
  1754. tmoveto(term.c.x, term.c.y);
  1755. /* reset scrolling region */
  1756. tsetscroll(0, row-1);
  1757. return (slide > 0);
  1758. }
  1759. void
  1760. xresize(int col, int row) {
  1761. xw.tw = MAX(1, 2*BORDER + col * xw.cw);
  1762. xw.th = MAX(1, 2*BORDER + row * xw.ch);
  1763. XftDrawChange(xw.xft_draw, xw.buf);
  1764. }
  1765. void
  1766. xloadcols(void) {
  1767. int i, r, g, b;
  1768. XRenderColor xft_color = { .alpha = 0 };
  1769. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1770. for(i = 0; i < LEN(colorname); i++) {
  1771. if(!colorname[i])
  1772. continue;
  1773. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
  1774. die("Could not allocate color '%s'\n", colorname[i]);
  1775. }
  1776. }
  1777. /* load colors [16-255] ; same colors as xterm */
  1778. for(i = 16, r = 0; r < 6; r++)
  1779. for(g = 0; g < 6; g++)
  1780. for(b = 0; b < 6; b++) {
  1781. xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1782. xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1783. xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1784. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
  1785. die("Could not allocate color %d\n", i);
  1786. }
  1787. i++;
  1788. }
  1789. for(r = 0; r < 24; r++, i++) {
  1790. xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
  1791. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
  1792. dc.xft_col[i] = dc.xft_col[256];
  1793. fprintf(stderr, "Could not allocate color %d\n", i);
  1794. }
  1795. }
  1796. }
  1797. void
  1798. xtermclear(int col1, int row1, int col2, int row2) {
  1799. XftDrawRect(xw.xft_draw,
  1800. &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
  1801. BORDER + col1 * xw.cw,
  1802. BORDER + row1 * xw.ch,
  1803. (col2-col1+1) * xw.cw,
  1804. (row2-row1+1) * xw.ch);
  1805. }
  1806. /*
  1807. * Absolute coordinates.
  1808. */
  1809. void
  1810. xclear(int x1, int y1, int x2, int y2) {
  1811. XftDrawRect(xw.xft_draw,
  1812. &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
  1813. x1, y1, x2-x1, y2-y1);
  1814. }
  1815. void
  1816. xclearborders(void) {
  1817. /* top and left border */
  1818. xclear(0, 0, BORDER, xw.h);
  1819. xclear(0, 0, xw.w, BORDER);
  1820. /* lower and right border */
  1821. xclear(BORDER, xw.th - 1, xw.w, xw.h);
  1822. /* Will just draw what hasn't been drawn by the previous call. */
  1823. xclear(xw.tw - 1, BORDER, xw.w, xw.h - xw.th - 2);
  1824. }
  1825. void
  1826. xhints(void) {
  1827. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1828. XWMHints wm = {.flags = InputHint, .input = 1};
  1829. XSizeHints *sizeh = NULL;
  1830. sizeh = XAllocSizeHints();
  1831. if(xw.isfixed == False) {
  1832. sizeh->flags = PSize | PResizeInc | PBaseSize;
  1833. sizeh->height = xw.h;
  1834. sizeh->width = xw.w;
  1835. sizeh->height_inc = xw.ch;
  1836. sizeh->width_inc = xw.cw;
  1837. sizeh->base_height = 2*BORDER;
  1838. sizeh->base_width = 2*BORDER;
  1839. } else {
  1840. sizeh->flags = PMaxSize | PMinSize;
  1841. sizeh->min_width = sizeh->max_width = xw.fw;
  1842. sizeh->min_height = sizeh->max_height = xw.fh;
  1843. }
  1844. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  1845. XFree(sizeh);
  1846. }
  1847. void
  1848. xinitfont(Font *f, char *fontstr) {
  1849. f->xft_set = XftFontOpenName(xw.dpy, xw.scr, fontstr);
  1850. if(!f->xft_set)
  1851. die("st: can't open font %s.\n", fontstr);
  1852. f->ascent = f->xft_set->ascent;
  1853. f->descent = f->xft_set->descent;
  1854. f->lbearing = 0;
  1855. f->rbearing = f->xft_set->max_advance_width;
  1856. }
  1857. void
  1858. initfonts(char *fontstr) {
  1859. char *fstr;
  1860. xinitfont(&dc.font, fontstr);
  1861. fstr = smstrcat(fontstr, ":weight=bold", NULL);
  1862. xinitfont(&dc.bfont, fstr);
  1863. free(fstr);
  1864. fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
  1865. xinitfont(&dc.ifont, fstr);
  1866. free(fstr);
  1867. fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
  1868. xinitfont(&dc.ibfont, fstr);
  1869. free(fstr);
  1870. }
  1871. void
  1872. xinit(void) {
  1873. XSetWindowAttributes attrs;
  1874. Cursor cursor;
  1875. Window parent;
  1876. int sw, sh, major, minor;
  1877. if(!(xw.dpy = XOpenDisplay(NULL)))
  1878. die("Can't open display\n");
  1879. xw.scr = XDefaultScreen(xw.dpy);
  1880. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  1881. /* font */
  1882. initfonts(FONT);
  1883. /* XXX: Assuming same size for bold font */
  1884. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1885. xw.ch = dc.font.ascent + dc.font.descent;
  1886. /* colors */
  1887. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1888. xloadcols();
  1889. /* adjust fixed window geometry */
  1890. if(xw.isfixed) {
  1891. sw = DisplayWidth(xw.dpy, xw.scr);
  1892. sh = DisplayHeight(xw.dpy, xw.scr);
  1893. if(xw.fx < 0)
  1894. xw.fx = sw + xw.fx - xw.fw - 1;
  1895. if(xw.fy < 0)
  1896. xw.fy = sh + xw.fy - xw.fh - 1;
  1897. xw.h = xw.fh;
  1898. xw.w = xw.fw;
  1899. } else {
  1900. /* window - default size */
  1901. xw.h = 2*BORDER + term.row * xw.ch;
  1902. xw.w = 2*BORDER + term.col * xw.cw;
  1903. xw.fx = 0;
  1904. xw.fy = 0;
  1905. }
  1906. attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
  1907. attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
  1908. attrs.bit_gravity = NorthWestGravity;
  1909. attrs.event_mask = FocusChangeMask | KeyPressMask
  1910. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1911. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  1912. attrs.colormap = xw.cmap;
  1913. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  1914. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  1915. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1916. xw.vis,
  1917. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1918. | CWColormap,
  1919. &attrs);
  1920. /* double buffering */
  1921. if(!XdbeQueryExtension(xw.dpy, &major, &minor))
  1922. die("Xdbe extension is not present\n");
  1923. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  1924. /* Xft rendering context */
  1925. xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  1926. /* input methods */
  1927. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1928. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1929. | XIMStatusNothing, XNClientWindow, xw.win,
  1930. XNFocusWindow, xw.win, NULL);
  1931. /* gc */
  1932. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1933. /* white cursor, black outline */
  1934. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1935. XDefineCursor(xw.dpy, xw.win, cursor);
  1936. XRecolorCursor(xw.dpy, cursor,
  1937. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1938. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1939. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1940. xresettitle();
  1941. XMapWindow(xw.dpy, xw.win);
  1942. xhints();
  1943. XSync(xw.dpy, 0);
  1944. }
  1945. void
  1946. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1947. int fg = base.fg, bg = base.bg, temp;
  1948. int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1949. Font *font = &dc.font;
  1950. XGlyphInfo extents;
  1951. /* only switch default fg/bg if term is in RV mode */
  1952. if(IS_SET(MODE_REVERSE)) {
  1953. if(fg == DefaultFG)
  1954. fg = DefaultBG;
  1955. if(bg == DefaultBG)
  1956. bg = DefaultFG;
  1957. }
  1958. if(base.mode & ATTR_REVERSE)
  1959. temp = fg, fg = bg, bg = temp;
  1960. if(base.mode & ATTR_BOLD) {
  1961. fg += 8;
  1962. font = &dc.bfont;
  1963. }
  1964. if(base.mode & ATTR_ITALIC)
  1965. font = &dc.ifont;
  1966. if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
  1967. font = &dc.ibfont;
  1968. XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen, &extents);
  1969. width = extents.xOff;
  1970. XftDrawRect(xw.xft_draw, &dc.xft_col[bg], winx, winy - font->ascent, width, xw.ch);
  1971. XftDrawStringUtf8(xw.xft_draw, &dc.xft_col[fg], font->xft_set, winx, winy, (FcChar8 *)s, bytelen);
  1972. if(base.mode & ATTR_UNDERLINE) {
  1973. XftDrawRect(xw.xft_draw, &dc.xft_col[fg], winx, winy+1,
  1974. width, 1);
  1975. }
  1976. }
  1977. void
  1978. xdrawcursor(void) {
  1979. static int oldx = 0;
  1980. static int oldy = 0;
  1981. int sl;
  1982. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1983. LIMIT(oldx, 0, term.col-1);
  1984. LIMIT(oldy, 0, term.row-1);
  1985. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1986. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1987. /* remove the old cursor */
  1988. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1989. sl = utf8size(term.line[oldy][oldx].c);
  1990. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1991. } else
  1992. xtermclear(oldx, oldy, oldx, oldy);
  1993. /* draw the new one */
  1994. if(!(term.c.state & CURSOR_HIDE)) {
  1995. if(!(xw.state & WIN_FOCUSED))
  1996. g.bg = DefaultUCS;
  1997. if(IS_SET(MODE_REVERSE))
  1998. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  1999. sl = utf8size(g.c);
  2000. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  2001. oldx = term.c.x, oldy = term.c.y;
  2002. }
  2003. }
  2004. void
  2005. xresettitle(void) {
  2006. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  2007. }
  2008. void
  2009. redraw(void) {
  2010. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  2011. xclearborders();
  2012. tfulldirt();
  2013. draw();
  2014. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2015. nanosleep(&tv, NULL);
  2016. }
  2017. void
  2018. draw(void) {
  2019. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  2020. drawregion(0, 0, term.col, term.row);
  2021. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  2022. }
  2023. void
  2024. drawregion(int x1, int y1, int x2, int y2) {
  2025. int ic, ib, x, y, ox, sl;
  2026. Glyph base, new;
  2027. char buf[DRAW_BUF_SIZ];
  2028. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
  2029. if((sel.alt && !alt) || (!sel.alt && alt))
  2030. ena_sel = 0;
  2031. if(!(xw.state & WIN_VISIBLE))
  2032. return;
  2033. for(y = y1; y < y2; y++) {
  2034. if(!term.dirty[y])
  2035. continue;
  2036. xtermclear(0, y, term.col, y);
  2037. term.dirty[y] = 0;
  2038. base = term.line[y][0];
  2039. ic = ib = ox = 0;
  2040. for(x = x1; x < x2; x++) {
  2041. new = term.line[y][x];
  2042. if(ena_sel && *(new.c) && selected(x, y))
  2043. new.mode ^= ATTR_REVERSE;
  2044. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  2045. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  2046. xdraws(buf, base, ox, y, ic, ib);
  2047. ic = ib = 0;
  2048. }
  2049. if(new.state & GLYPH_SET) {
  2050. if(ib == 0) {
  2051. ox = x;
  2052. base = new;
  2053. }
  2054. sl = utf8size(new.c);
  2055. memcpy(buf+ib, new.c, sl);
  2056. ib += sl;
  2057. ++ic;
  2058. }
  2059. }
  2060. if(ib > 0)
  2061. xdraws(buf, base, ox, y, ic, ib);
  2062. }
  2063. xdrawcursor();
  2064. }
  2065. void
  2066. expose(XEvent *ev) {
  2067. XExposeEvent *e = &ev->xexpose;
  2068. if(xw.state & WIN_REDRAW) {
  2069. if(!e->count)
  2070. xw.state &= ~WIN_REDRAW;
  2071. }
  2072. }
  2073. void
  2074. visibility(XEvent *ev) {
  2075. XVisibilityEvent *e = &ev->xvisibility;
  2076. if(e->state == VisibilityFullyObscured)
  2077. xw.state &= ~WIN_VISIBLE;
  2078. else if(!(xw.state & WIN_VISIBLE))
  2079. /* need a full redraw for next Expose, not just a buf copy */
  2080. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2081. }
  2082. void
  2083. unmap(XEvent *ev) {
  2084. xw.state &= ~WIN_VISIBLE;
  2085. }
  2086. void
  2087. xseturgency(int add) {
  2088. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2089. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2090. XSetWMHints(xw.dpy, xw.win, h);
  2091. XFree(h);
  2092. }
  2093. void
  2094. focus(XEvent *ev) {
  2095. if(ev->type == FocusIn) {
  2096. xw.state |= WIN_FOCUSED;
  2097. xseturgency(0);
  2098. } else
  2099. xw.state &= ~WIN_FOCUSED;
  2100. }
  2101. char*
  2102. kmap(KeySym k, uint state) {
  2103. int i;
  2104. state &= ~Mod2Mask;
  2105. for(i = 0; i < LEN(key); i++) {
  2106. uint mask = key[i].mask;
  2107. if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
  2108. return (char*)key[i].s;
  2109. }
  2110. return NULL;
  2111. }
  2112. void
  2113. kpress(XEvent *ev) {
  2114. XKeyEvent *e = &ev->xkey;
  2115. KeySym ksym;
  2116. char buf[32];
  2117. char *customkey;
  2118. int len;
  2119. int meta;
  2120. int shift;
  2121. Status status;
  2122. if (IS_SET(MODE_KBDLOCK))
  2123. return;
  2124. meta = e->state & Mod1Mask;
  2125. shift = e->state & ShiftMask;
  2126. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  2127. /* 1. custom keys from config.h */
  2128. if((customkey = kmap(ksym, e->state)))
  2129. ttywrite(customkey, strlen(customkey));
  2130. /* 2. hardcoded (overrides X lookup) */
  2131. else
  2132. switch(ksym) {
  2133. case XK_Up:
  2134. case XK_Down:
  2135. case XK_Left:
  2136. case XK_Right:
  2137. /* XXX: shift up/down doesn't work */
  2138. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
  2139. ttywrite(buf, 3);
  2140. break;
  2141. case XK_Insert:
  2142. if(shift)
  2143. selpaste();
  2144. break;
  2145. case XK_Return:
  2146. if(IS_SET(MODE_CRLF))
  2147. ttywrite("\r\n", 2);
  2148. else
  2149. ttywrite("\r", 1);
  2150. break;
  2151. /* 3. X lookup */
  2152. default:
  2153. if(len > 0) {
  2154. if(meta && len == 1)
  2155. ttywrite("\033", 1);
  2156. ttywrite(buf, len);
  2157. }
  2158. break;
  2159. }
  2160. }
  2161. void
  2162. cmessage(XEvent *e) {
  2163. /* See xembed specs
  2164. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2165. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2166. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2167. xw.state |= WIN_FOCUSED;
  2168. xseturgency(0);
  2169. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2170. xw.state &= ~WIN_FOCUSED;
  2171. }
  2172. }
  2173. }
  2174. void
  2175. resize(XEvent *e) {
  2176. int col, row;
  2177. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2178. return;
  2179. xw.w = e->xconfigure.width;
  2180. xw.h = e->xconfigure.height;
  2181. col = (xw.w - 2*BORDER) / xw.cw;
  2182. row = (xw.h - 2*BORDER) / xw.ch;
  2183. if(col == term.col && row == term.row)
  2184. return;
  2185. tresize(col, row);
  2186. xresize(col, row);
  2187. xclearborders();
  2188. ttyresize();
  2189. }
  2190. void
  2191. run(void) {
  2192. XEvent ev;
  2193. fd_set rfd;
  2194. int xfd = XConnectionNumber(xw.dpy), i;
  2195. struct timeval drawtimeout, *tv = NULL;
  2196. for(i = 0;; i++) {
  2197. FD_ZERO(&rfd);
  2198. FD_SET(cmdfd, &rfd);
  2199. FD_SET(xfd, &rfd);
  2200. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  2201. if(errno == EINTR)
  2202. continue;
  2203. die("select failed: %s\n", SERRNO);
  2204. }
  2205. /*
  2206. * Stop after a certain number of reads so the user does not
  2207. * feel like the system is stuttering.
  2208. */
  2209. if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
  2210. ttyread();
  2211. /*
  2212. * Just wait a bit so it isn't disturbing the
  2213. * user and the system is able to write something.
  2214. */
  2215. drawtimeout.tv_sec = 0;
  2216. drawtimeout.tv_usec = 5;
  2217. tv = &drawtimeout;
  2218. continue;
  2219. }
  2220. i = 0;
  2221. tv = NULL;
  2222. while(XPending(xw.dpy)) {
  2223. XNextEvent(xw.dpy, &ev);
  2224. if(XFilterEvent(&ev, xw.win))
  2225. continue;
  2226. if(handler[ev.type])
  2227. (handler[ev.type])(&ev);
  2228. }
  2229. draw();
  2230. XFlush(xw.dpy);
  2231. }
  2232. }
  2233. int
  2234. main(int argc, char *argv[]) {
  2235. int i, bitm, xr, yr;
  2236. uint wr, hr;
  2237. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2238. xw.isfixed = False;
  2239. for(i = 1; i < argc; i++) {
  2240. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2241. case 't':
  2242. if(++i < argc) opt_title = argv[i];
  2243. break;
  2244. case 'c':
  2245. if(++i < argc) opt_class = argv[i];
  2246. break;
  2247. case 'w':
  2248. if(++i < argc) opt_embed = argv[i];
  2249. break;
  2250. case 'f':
  2251. if(++i < argc) opt_io = argv[i];
  2252. break;
  2253. case 'e':
  2254. /* eat every remaining arguments */
  2255. if(++i < argc) opt_cmd = &argv[i];
  2256. goto run;
  2257. case 'g':
  2258. if(++i >= argc)
  2259. break;
  2260. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2261. if(bitm & XValue)
  2262. xw.fx = xr;
  2263. if(bitm & YValue)
  2264. xw.fy = yr;
  2265. if(bitm & WidthValue)
  2266. xw.fw = (int)wr;
  2267. if(bitm & HeightValue)
  2268. xw.fh = (int)hr;
  2269. if(bitm & XNegative && xw.fx == 0)
  2270. xw.fx = -1;
  2271. if(bitm & XNegative && xw.fy == 0)
  2272. xw.fy = -1;
  2273. if(xw.fh != 0 && xw.fw != 0)
  2274. xw.isfixed = True;
  2275. break;
  2276. case 'v':
  2277. default:
  2278. die(USAGE);
  2279. }
  2280. }
  2281. run:
  2282. setlocale(LC_CTYPE, "");
  2283. tnew(80, 24);
  2284. ttynew();
  2285. xinit();
  2286. selinit();
  2287. run();
  2288. return 0;
  2289. }