Simple Terminal from SuckLess
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.

2313 lines
51 KiB

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