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.

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