Simple Terminal from SuckLess
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.

2443 lines
54 KiB

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