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.

2298 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 '2':
  1325. /*
  1326. * TODO: Handle special chars in string, like umlauts.
  1327. */
  1328. if(p[1] == ';') {
  1329. if(!strncmp(strescseq.buf, "settitle ", 9)) {
  1330. XStoreName(xw.dpy, xw.win, strescseq.buf+11);
  1331. } else {
  1332. XStoreName(xw.dpy, xw.win, strescseq.buf+2);
  1333. }
  1334. }
  1335. break;
  1336. case ';':
  1337. XStoreName(xw.dpy, xw.win, strescseq.buf+1);
  1338. break;
  1339. case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
  1340. break;
  1341. default:
  1342. fprintf(stderr, "erresc: unknown str ");
  1343. strdump();
  1344. break;
  1345. }
  1346. break;
  1347. case 'P': /* DSC -- Device Control String */
  1348. case '_': /* APC -- Application Program Command */
  1349. case '^': /* PM -- Privacy Message */
  1350. default:
  1351. fprintf(stderr, "erresc: unknown str ");
  1352. strdump();
  1353. /* die(""); */
  1354. break;
  1355. }
  1356. }
  1357. void
  1358. strparse(void) {
  1359. /*
  1360. * TODO: Implement parsing like for CSI when required.
  1361. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1362. */
  1363. return;
  1364. }
  1365. void
  1366. strdump(void) {
  1367. int i;
  1368. printf("ESC%c", strescseq.type);
  1369. for(i = 0; i < strescseq.len; i++) {
  1370. uint c = strescseq.buf[i] & 0xff;
  1371. if(isprint(c)) putchar(c);
  1372. else if(c == '\n') printf("(\\n)");
  1373. else if(c == '\r') printf("(\\r)");
  1374. else if(c == 0x1b) printf("(\\e)");
  1375. else printf("(%02x)", c);
  1376. }
  1377. printf("ESC\\\n");
  1378. }
  1379. void
  1380. strreset(void) {
  1381. memset(&strescseq, 0, sizeof(strescseq));
  1382. }
  1383. void
  1384. tputtab(void) {
  1385. unsigned x;
  1386. for (x = term.c.x + 1; x < term.col && !term.tabs[x]; ++x)
  1387. /* nothing */ ;
  1388. tmoveto(x, term.c.y);
  1389. }
  1390. void
  1391. tputc(char *c) {
  1392. char ascii = *c;
  1393. if(term.esc & ESC_START) {
  1394. if(term.esc & ESC_CSI) {
  1395. csiescseq.buf[csiescseq.len++] = ascii;
  1396. if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
  1397. term.esc = 0;
  1398. csiparse(), csihandle();
  1399. }
  1400. } else if(term.esc & ESC_STR) {
  1401. switch(ascii) {
  1402. case '\033':
  1403. term.esc = ESC_START | ESC_STR_END;
  1404. break;
  1405. case '\a': /* backwards compatibility to xterm */
  1406. term.esc = 0;
  1407. strhandle();
  1408. break;
  1409. default:
  1410. strescseq.buf[strescseq.len++] = ascii;
  1411. if (strescseq.len+1 >= STR_BUF_SIZ) {
  1412. term.esc = 0;
  1413. strhandle();
  1414. }
  1415. }
  1416. } else if(term.esc & ESC_STR_END) {
  1417. term.esc = 0;
  1418. if(ascii == '\\')
  1419. strhandle();
  1420. } else if(term.esc & ESC_ALTCHARSET) {
  1421. switch(ascii) {
  1422. case '0': /* Line drawing crap */
  1423. term.c.attr.mode |= ATTR_GFX;
  1424. break;
  1425. case 'B': /* Back to regular text */
  1426. term.c.attr.mode &= ~ATTR_GFX;
  1427. break;
  1428. default:
  1429. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1430. }
  1431. term.esc = 0;
  1432. } else {
  1433. switch(ascii) {
  1434. case '[':
  1435. term.esc |= ESC_CSI;
  1436. break;
  1437. case 'P': /* DCS -- Device Control String */
  1438. case '_': /* APC -- Application Program Command */
  1439. case '^': /* PM -- Privacy Message */
  1440. case ']': /* OSC -- Operating System Command */
  1441. strreset();
  1442. strescseq.type = ascii;
  1443. term.esc |= ESC_STR;
  1444. break;
  1445. case '(':
  1446. term.esc |= ESC_ALTCHARSET;
  1447. break;
  1448. case 'D': /* IND -- Linefeed */
  1449. if(term.c.y == term.bot)
  1450. tscrollup(term.top, 1);
  1451. else
  1452. tmoveto(term.c.x, term.c.y+1);
  1453. term.esc = 0;
  1454. break;
  1455. case 'E': /* NEL -- Next line */
  1456. tnewline(1); /* always go to first col */
  1457. term.esc = 0;
  1458. break;
  1459. case 'H': /* HTS -- Horizontal tab stop */
  1460. term.tabs[term.c.x] = 1;
  1461. term.esc = 0;
  1462. break;
  1463. case 'M': /* RI -- Reverse index */
  1464. if(term.c.y == term.top)
  1465. tscrolldown(term.top, 1);
  1466. else
  1467. tmoveto(term.c.x, term.c.y-1);
  1468. term.esc = 0;
  1469. break;
  1470. case 'c': /* RIS -- Reset to inital state */
  1471. treset();
  1472. term.esc = 0;
  1473. break;
  1474. case '=': /* DECPAM -- Application keypad */
  1475. term.mode |= MODE_APPKEYPAD;
  1476. term.esc = 0;
  1477. break;
  1478. case '>': /* DECPNM -- Normal keypad */
  1479. term.mode &= ~MODE_APPKEYPAD;
  1480. term.esc = 0;
  1481. break;
  1482. case '7': /* DECSC -- Save Cursor */
  1483. tcursor(CURSOR_SAVE);
  1484. term.esc = 0;
  1485. break;
  1486. case '8': /* DECRC -- Restore Cursor */
  1487. tcursor(CURSOR_LOAD);
  1488. term.esc = 0;
  1489. break;
  1490. case '\\': /* ST -- Stop */
  1491. term.esc = 0;
  1492. break;
  1493. default:
  1494. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1495. (uchar) ascii, isprint(ascii)?ascii:'.');
  1496. term.esc = 0;
  1497. }
  1498. }
  1499. } else {
  1500. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1501. sel.bx = -1;
  1502. switch(ascii) {
  1503. case '\t':
  1504. tputtab();
  1505. break;
  1506. case '\b':
  1507. tmoveto(term.c.x-1, term.c.y);
  1508. break;
  1509. case '\r':
  1510. tmoveto(0, term.c.y);
  1511. break;
  1512. case '\f':
  1513. case '\v':
  1514. case '\n':
  1515. /* go to first col if the mode is set */
  1516. tnewline(IS_SET(MODE_CRLF));
  1517. break;
  1518. case '\a':
  1519. if(!(xw.state & WIN_FOCUSED))
  1520. xseturgency(1);
  1521. break;
  1522. case '\033':
  1523. csireset();
  1524. term.esc = ESC_START;
  1525. break;
  1526. default:
  1527. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1528. tnewline(1); /* always go to first col */
  1529. tsetchar(c);
  1530. if(term.c.x+1 < term.col)
  1531. tmoveto(term.c.x+1, term.c.y);
  1532. else
  1533. term.c.state |= CURSOR_WRAPNEXT;
  1534. }
  1535. }
  1536. }
  1537. int
  1538. tresize(int col, int row) {
  1539. int i, x;
  1540. int minrow = MIN(row, term.row);
  1541. int mincol = MIN(col, term.col);
  1542. int slide = term.c.y - row + 1;
  1543. if(col < 1 || row < 1)
  1544. return 0;
  1545. /* free unneeded rows */
  1546. i = 0;
  1547. if(slide > 0) {
  1548. /* slide screen to keep cursor where we expect it -
  1549. * tscrollup would work here, but we can optimize to
  1550. * memmove because we're freeing the earlier lines */
  1551. for(/* i = 0 */; i < slide; i++) {
  1552. free(term.line[i]);
  1553. free(term.alt[i]);
  1554. }
  1555. memmove(term.line, term.line + slide, row * sizeof(Line));
  1556. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1557. }
  1558. for(i += row; i < term.row; i++) {
  1559. free(term.line[i]);
  1560. free(term.alt[i]);
  1561. }
  1562. /* resize to new height */
  1563. term.line = realloc(term.line, row * sizeof(Line));
  1564. term.alt = realloc(term.alt, row * sizeof(Line));
  1565. term.dirty = realloc(term.dirty, row * sizeof(*term.dirty));
  1566. term.tabs = realloc(term.tabs, col * sizeof(*term.tabs));
  1567. /* resize each row to new width, zero-pad if needed */
  1568. for(i = 0; i < minrow; i++) {
  1569. term.dirty[i] = 1;
  1570. term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
  1571. term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
  1572. for(x = mincol; x < col; x++) {
  1573. term.line[i][x].state = 0;
  1574. term.alt[i][x].state = 0;
  1575. }
  1576. }
  1577. /* allocate any new rows */
  1578. for(/* i == minrow */; i < row; i++) {
  1579. term.dirty[i] = 1;
  1580. term.line[i] = calloc(col, sizeof(Glyph));
  1581. term.alt [i] = calloc(col, sizeof(Glyph));
  1582. }
  1583. if (col > term.col) {
  1584. bool *bp = term.tabs + term.col;
  1585. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1586. while (--bp > term.tabs && !*bp)
  1587. /* nothing */ ;
  1588. for (bp += TAB; bp < term.tabs + col; bp += TAB)
  1589. *bp = 1;
  1590. }
  1591. /* update terminal size */
  1592. term.col = col, term.row = row;
  1593. /* make use of the LIMIT in tmoveto */
  1594. tmoveto(term.c.x, term.c.y);
  1595. /* reset scrolling region */
  1596. tsetscroll(0, row-1);
  1597. return (slide > 0);
  1598. }
  1599. void
  1600. xresize(int col, int row) {
  1601. xw.w = MAX(1, 2*BORDER + col * xw.cw);
  1602. xw.h = MAX(1, 2*BORDER + row * xw.ch);
  1603. }
  1604. void
  1605. xloadcols(void) {
  1606. int i, r, g, b;
  1607. XColor color;
  1608. ulong white = WhitePixel(xw.dpy, xw.scr);
  1609. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1610. for(i = 0; i < LEN(colorname); i++) {
  1611. if(!colorname[i])
  1612. continue;
  1613. if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
  1614. dc.col[i] = white;
  1615. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1616. } else
  1617. dc.col[i] = color.pixel;
  1618. }
  1619. /* load colors [16-255] ; same colors as xterm */
  1620. for(i = 16, r = 0; r < 6; r++)
  1621. for(g = 0; g < 6; g++)
  1622. for(b = 0; b < 6; b++) {
  1623. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1624. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1625. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1626. if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1627. dc.col[i] = white;
  1628. fprintf(stderr, "Could not allocate color %d\n", i);
  1629. } else
  1630. dc.col[i] = color.pixel;
  1631. i++;
  1632. }
  1633. for(r = 0; r < 24; r++, i++) {
  1634. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1635. if (!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1636. dc.col[i] = white;
  1637. fprintf(stderr, "Could not allocate color %d\n", i);
  1638. } else
  1639. dc.col[i] = color.pixel;
  1640. }
  1641. }
  1642. void
  1643. xclear(int x1, int y1, int x2, int y2) {
  1644. XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
  1645. XFillRectangle(xw.dpy, xw.buf, dc.gc,
  1646. BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
  1647. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1648. }
  1649. void
  1650. xhints(void) {
  1651. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1652. XWMHints wm = {.flags = InputHint, .input = 1};
  1653. XSizeHints size = {
  1654. .flags = PSize | PResizeInc | PBaseSize,
  1655. .height = xw.h,
  1656. .width = xw.w,
  1657. .height_inc = xw.ch,
  1658. .width_inc = xw.cw,
  1659. .base_height = 2*BORDER,
  1660. .base_width = 2*BORDER,
  1661. };
  1662. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
  1663. }
  1664. XFontSet
  1665. xinitfont(char *fontstr) {
  1666. XFontSet set;
  1667. char *def, **missing;
  1668. int n;
  1669. missing = NULL;
  1670. set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
  1671. if(missing) {
  1672. while(n--)
  1673. fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
  1674. XFreeStringList(missing);
  1675. }
  1676. return set;
  1677. }
  1678. void
  1679. xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
  1680. XFontStruct **xfonts;
  1681. char **font_names;
  1682. int i, n;
  1683. *ascent = *descent = *lbearing = *rbearing = 0;
  1684. n = XFontsOfFontSet(set, &xfonts, &font_names);
  1685. for(i = 0; i < n; i++) {
  1686. *ascent = MAX(*ascent, (*xfonts)->ascent);
  1687. *descent = MAX(*descent, (*xfonts)->descent);
  1688. *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
  1689. *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
  1690. xfonts++;
  1691. }
  1692. }
  1693. void
  1694. initfonts(char *fontstr, char *bfontstr) {
  1695. if((dc.font.set = xinitfont(fontstr)) == NULL ||
  1696. (dc.bfont.set = xinitfont(bfontstr)) == NULL)
  1697. die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
  1698. xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
  1699. &dc.font.lbearing, &dc.font.rbearing);
  1700. xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
  1701. &dc.bfont.lbearing, &dc.bfont.rbearing);
  1702. }
  1703. void
  1704. xinit(void) {
  1705. XSetWindowAttributes attrs;
  1706. Cursor cursor;
  1707. Window parent;
  1708. if(!(xw.dpy = XOpenDisplay(NULL)))
  1709. die("Can't open display\n");
  1710. xw.scr = XDefaultScreen(xw.dpy);
  1711. /* font */
  1712. initfonts(FONT, BOLDFONT);
  1713. /* XXX: Assuming same size for bold font */
  1714. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1715. xw.ch = dc.font.ascent + dc.font.descent;
  1716. /* colors */
  1717. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1718. xloadcols();
  1719. /* window - default size */
  1720. xw.h = 2*BORDER + term.row * xw.ch;
  1721. xw.w = 2*BORDER + term.col * xw.cw;
  1722. attrs.background_pixel = dc.col[DefaultBG];
  1723. attrs.border_pixel = dc.col[DefaultBG];
  1724. attrs.bit_gravity = NorthWestGravity;
  1725. attrs.event_mask = FocusChangeMask | KeyPressMask
  1726. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1727. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask
  1728. | EnterWindowMask | LeaveWindowMask;
  1729. attrs.colormap = xw.cmap;
  1730. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  1731. xw.win = XCreateWindow(xw.dpy, parent, 0, 0,
  1732. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1733. XDefaultVisual(xw.dpy, xw.scr),
  1734. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1735. | CWColormap,
  1736. &attrs);
  1737. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  1738. /* input methods */
  1739. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1740. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1741. | XIMStatusNothing, XNClientWindow, xw.win,
  1742. XNFocusWindow, xw.win, NULL);
  1743. /* gc */
  1744. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1745. /* white cursor, black outline */
  1746. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1747. XDefineCursor(xw.dpy, xw.win, cursor);
  1748. XRecolorCursor(xw.dpy, cursor,
  1749. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1750. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1751. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1752. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1753. XMapWindow(xw.dpy, xw.win);
  1754. xhints();
  1755. XSync(xw.dpy, 0);
  1756. }
  1757. void
  1758. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1759. int fg = base.fg, bg = base.bg, temp;
  1760. int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1761. XFontSet fontset = dc.font.set;
  1762. int i;
  1763. /* only switch default fg/bg if term is in RV mode */
  1764. if(IS_SET(MODE_REVERSE)) {
  1765. if(fg == DefaultFG)
  1766. fg = DefaultBG;
  1767. if(bg == DefaultBG)
  1768. bg = DefaultFG;
  1769. }
  1770. if(base.mode & ATTR_REVERSE)
  1771. temp = fg, fg = bg, bg = temp;
  1772. if(base.mode & ATTR_BOLD) {
  1773. fg += 8;
  1774. fontset = dc.bfont.set;
  1775. }
  1776. XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
  1777. XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
  1778. if(base.mode & ATTR_GFX) {
  1779. for(i = 0; i < bytelen; i++) {
  1780. char c = gfx[(uint)s[i] % 256];
  1781. if(c)
  1782. s[i] = c;
  1783. else if(s[i] > 0x5f)
  1784. s[i] -= 0x5f;
  1785. }
  1786. }
  1787. XmbDrawImageString(xw.dpy, xw.buf, fontset, dc.gc, winx, winy, s, bytelen);
  1788. if(base.mode & ATTR_UNDERLINE)
  1789. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1790. }
  1791. /* copy buffer pixmap to screen pixmap */
  1792. void
  1793. xcopy() {
  1794. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  1795. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  1796. }
  1797. void
  1798. xdrawcursor(void) {
  1799. static int oldx = 0;
  1800. static int oldy = 0;
  1801. int sl;
  1802. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1803. LIMIT(oldx, 0, term.col-1);
  1804. LIMIT(oldy, 0, term.row-1);
  1805. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1806. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1807. /* remove the old cursor */
  1808. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1809. sl = utf8size(term.line[oldy][oldx].c);
  1810. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1811. } else
  1812. xclear(oldx, oldy, oldx, oldy);
  1813. xcopy(oldx, oldy, 1, 1);
  1814. /* draw the new one */
  1815. if(!(term.c.state & CURSOR_HIDE)) {
  1816. if(!(xw.state & WIN_FOCUSED))
  1817. g.bg = DefaultUCS;
  1818. if(IS_SET(MODE_REVERSE))
  1819. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  1820. sl = utf8size(g.c);
  1821. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1822. oldx = term.c.x, oldy = term.c.y;
  1823. }
  1824. xcopy(term.c.x, term.c.y, 1, 1);
  1825. }
  1826. void
  1827. draw() {
  1828. drawregion(0, 0, term.col, term.row);
  1829. xcopy();
  1830. gettimeofday(&xw.lastdraw, NULL);
  1831. }
  1832. void
  1833. drawregion(int x1, int y1, int x2, int y2) {
  1834. int ic, ib, x, y, ox, sl;
  1835. Glyph base, new;
  1836. char buf[DRAW_BUF_SIZ];
  1837. if(!(xw.state & WIN_VISIBLE))
  1838. return;
  1839. for(y = y1; y < y2; y++) {
  1840. if(!term.dirty[y])
  1841. continue;
  1842. xclear(0, y, term.col, y);
  1843. term.dirty[y] = 0;
  1844. base = term.line[y][0];
  1845. ic = ib = ox = 0;
  1846. for(x = x1; x < x2; x++) {
  1847. new = term.line[y][x];
  1848. if(sel.bx != -1 && *(new.c) && selected(x, y))
  1849. new.mode ^= ATTR_REVERSE;
  1850. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1851. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1852. xdraws(buf, base, ox, y, ic, ib);
  1853. ic = ib = 0;
  1854. }
  1855. if(new.state & GLYPH_SET) {
  1856. if(ib == 0) {
  1857. ox = x;
  1858. base = new;
  1859. }
  1860. sl = utf8size(new.c);
  1861. memcpy(buf+ib, new.c, sl);
  1862. ib += sl;
  1863. ++ic;
  1864. }
  1865. }
  1866. if(ib > 0)
  1867. xdraws(buf, base, ox, y, ic, ib);
  1868. }
  1869. xdrawcursor();
  1870. }
  1871. void
  1872. expose(XEvent *ev) {
  1873. XExposeEvent *e = &ev->xexpose;
  1874. if(xw.state & WIN_REDRAW) {
  1875. if(!e->count)
  1876. xw.state &= ~WIN_REDRAW;
  1877. }
  1878. xcopy();
  1879. }
  1880. void
  1881. visibility(XEvent *ev) {
  1882. XVisibilityEvent *e = &ev->xvisibility;
  1883. if(e->state == VisibilityFullyObscured)
  1884. xw.state &= ~WIN_VISIBLE;
  1885. else if(!(xw.state & WIN_VISIBLE))
  1886. /* need a full redraw for next Expose, not just a buf copy */
  1887. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1888. }
  1889. void
  1890. unmap(XEvent *ev) {
  1891. xw.state &= ~WIN_VISIBLE;
  1892. }
  1893. void
  1894. xseturgency(int add) {
  1895. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1896. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1897. XSetWMHints(xw.dpy, xw.win, h);
  1898. XFree(h);
  1899. }
  1900. void
  1901. focus(XEvent *ev) {
  1902. if(ev->type == FocusIn) {
  1903. xw.state |= WIN_FOCUSED;
  1904. xseturgency(0);
  1905. } else
  1906. xw.state &= ~WIN_FOCUSED;
  1907. draw();
  1908. }
  1909. char*
  1910. kmap(KeySym k, uint state) {
  1911. int i;
  1912. state &= ~Mod2Mask;
  1913. for(i = 0; i < LEN(key); i++) {
  1914. uint mask = key[i].mask;
  1915. if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
  1916. return (char*)key[i].s;
  1917. }
  1918. return NULL;
  1919. }
  1920. void
  1921. kpress(XEvent *ev) {
  1922. XKeyEvent *e = &ev->xkey;
  1923. KeySym ksym;
  1924. char buf[32];
  1925. char *customkey;
  1926. int len;
  1927. int meta;
  1928. int shift;
  1929. Status status;
  1930. meta = e->state & Mod1Mask;
  1931. shift = e->state & ShiftMask;
  1932. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1933. /* 1. custom keys from config.h */
  1934. if((customkey = kmap(ksym, e->state)))
  1935. ttywrite(customkey, strlen(customkey));
  1936. /* 2. hardcoded (overrides X lookup) */
  1937. else
  1938. switch(ksym) {
  1939. case XK_Up:
  1940. case XK_Down:
  1941. case XK_Left:
  1942. case XK_Right:
  1943. /* XXX: shift up/down doesn't work */
  1944. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
  1945. ttywrite(buf, 3);
  1946. break;
  1947. case XK_Insert:
  1948. if(shift)
  1949. selpaste();
  1950. break;
  1951. case XK_Return:
  1952. if(IS_SET(MODE_CRLF))
  1953. ttywrite("\r\n", 2);
  1954. else
  1955. ttywrite("\r", 1);
  1956. break;
  1957. /* 3. X lookup */
  1958. default:
  1959. if(len > 0) {
  1960. if(meta && len == 1)
  1961. ttywrite("\033", 1);
  1962. ttywrite(buf, len);
  1963. }
  1964. break;
  1965. }
  1966. }
  1967. void
  1968. cmessage(XEvent *e) {
  1969. /* See xembed specs
  1970. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  1971. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1972. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1973. xw.state |= WIN_FOCUSED;
  1974. xseturgency(0);
  1975. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1976. xw.state &= ~WIN_FOCUSED;
  1977. }
  1978. draw();
  1979. }
  1980. }
  1981. void
  1982. resize(XEvent *e) {
  1983. int col, row;
  1984. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  1985. return;
  1986. xw.w = e->xconfigure.width;
  1987. xw.h = e->xconfigure.height;
  1988. col = (xw.w - 2*BORDER) / xw.cw;
  1989. row = (xw.h - 2*BORDER) / xw.ch;
  1990. if(col == term.col && row == term.row)
  1991. return;
  1992. if(tresize(col, row))
  1993. draw();
  1994. ttyresize(col, row);
  1995. xresize(col, row);
  1996. }
  1997. bool
  1998. last_draw_too_old(void) {
  1999. struct timeval now;
  2000. gettimeofday(&now, NULL);
  2001. return TIMEDIFF(now, xw.lastdraw) >= DRAW_TIMEOUT/1000;
  2002. }
  2003. void
  2004. run(void) {
  2005. XEvent ev;
  2006. fd_set rfd;
  2007. int xfd = XConnectionNumber(xw.dpy);
  2008. struct timeval timeout = {0};
  2009. bool stuff_to_print = 0;
  2010. for(;;) {
  2011. FD_ZERO(&rfd);
  2012. FD_SET(cmdfd, &rfd);
  2013. FD_SET(xfd, &rfd);
  2014. timeout.tv_sec = 0;
  2015. timeout.tv_usec = SELECT_TIMEOUT;
  2016. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, &timeout) < 0) {
  2017. if(errno == EINTR)
  2018. continue;
  2019. die("select failed: %s\n", SERRNO);
  2020. }
  2021. if(FD_ISSET(cmdfd, &rfd)) {
  2022. ttyread();
  2023. stuff_to_print = 1;
  2024. }
  2025. if(stuff_to_print && last_draw_too_old()) {
  2026. stuff_to_print = 0;
  2027. draw();
  2028. }
  2029. while(XPending(xw.dpy)) {
  2030. XNextEvent(xw.dpy, &ev);
  2031. if(XFilterEvent(&ev, xw.win))
  2032. continue;
  2033. if(handler[ev.type])
  2034. (handler[ev.type])(&ev);
  2035. }
  2036. }
  2037. }
  2038. int
  2039. main(int argc, char *argv[]) {
  2040. int i;
  2041. for(i = 1; i < argc; i++) {
  2042. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2043. case 't':
  2044. if(++i < argc) opt_title = argv[i];
  2045. break;
  2046. case 'c':
  2047. if(++i < argc) opt_class = argv[i];
  2048. break;
  2049. case 'w':
  2050. if(++i < argc) opt_embed = argv[i];
  2051. break;
  2052. case 'e':
  2053. /* eat every remaining arguments */
  2054. if(++i < argc) opt_cmd = &argv[i];
  2055. goto run;
  2056. case 'v':
  2057. default:
  2058. die(USAGE);
  2059. }
  2060. }
  2061. run:
  2062. setlocale(LC_CTYPE, "");
  2063. tnew(80, 24);
  2064. ttynew();
  2065. xinit();
  2066. selinit();
  2067. run();
  2068. return 0;
  2069. }