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.

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