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.

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