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.

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