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.

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