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.

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