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.

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