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.

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