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.

2630 lines
58 KiB

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