My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2362 lines
53 KiB

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