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.

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