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.

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