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.

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