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.

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