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.

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