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.

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