My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2491 lines
56 KiB

13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
15 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
  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*, int);
  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, charsize);
  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. tclearregion(0, 0, term.col-1, term.row-1);
  852. }
  853. void
  854. tnew(int col, int row) {
  855. /* set screen size */
  856. term.row = row, term.col = col;
  857. term.line = xmalloc(term.row * sizeof(Line));
  858. term.alt = xmalloc(term.row * sizeof(Line));
  859. term.dirty = xmalloc(term.row * sizeof(*term.dirty));
  860. term.tabs = xmalloc(term.col * sizeof(*term.tabs));
  861. for(row = 0; row < term.row; row++) {
  862. term.line[row] = xmalloc(term.col * sizeof(Glyph));
  863. term.alt [row] = xmalloc(term.col * sizeof(Glyph));
  864. term.dirty[row] = 0;
  865. }
  866. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  867. /* setup screen */
  868. treset();
  869. }
  870. void
  871. tswapscreen(void) {
  872. Line* tmp = term.line;
  873. term.line = term.alt;
  874. term.alt = tmp;
  875. term.mode ^= MODE_ALTSCREEN;
  876. tfulldirt();
  877. }
  878. void
  879. tscrolldown(int orig, int n) {
  880. int i;
  881. Line temp;
  882. LIMIT(n, 0, term.bot-orig+1);
  883. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  884. for(i = term.bot; i >= orig+n; i--) {
  885. temp = term.line[i];
  886. term.line[i] = term.line[i-n];
  887. term.line[i-n] = temp;
  888. term.dirty[i] = 1;
  889. term.dirty[i-n] = 1;
  890. }
  891. selscroll(orig, n);
  892. }
  893. void
  894. tscrollup(int orig, int n) {
  895. int i;
  896. Line temp;
  897. LIMIT(n, 0, term.bot-orig+1);
  898. tclearregion(0, orig, term.col-1, orig+n-1);
  899. for(i = orig; i <= term.bot-n; i++) {
  900. temp = term.line[i];
  901. term.line[i] = term.line[i+n];
  902. term.line[i+n] = temp;
  903. term.dirty[i] = 1;
  904. term.dirty[i+n] = 1;
  905. }
  906. selscroll(orig, -n);
  907. }
  908. void
  909. selscroll(int orig, int n) {
  910. if(sel.bx == -1)
  911. return;
  912. if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
  913. if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
  914. sel.bx = -1;
  915. return;
  916. }
  917. if(sel.by < term.top) {
  918. sel.by = term.top;
  919. sel.bx = 0;
  920. }
  921. if(sel.ey > term.bot) {
  922. sel.ey = term.bot;
  923. sel.ex = term.col;
  924. }
  925. sel.b.y = sel.by, sel.b.x = sel.bx;
  926. sel.e.y = sel.ey, sel.e.x = sel.ex;
  927. }
  928. }
  929. void
  930. tnewline(int first_col) {
  931. int y = term.c.y;
  932. if(y == term.bot)
  933. tscrollup(term.top, 1);
  934. else
  935. y++;
  936. tmoveto(first_col ? 0 : term.c.x, y);
  937. }
  938. void
  939. csiparse(void) {
  940. /* int noarg = 1; */
  941. char *p = csiescseq.buf;
  942. csiescseq.narg = 0;
  943. if(*p == '?')
  944. csiescseq.priv = 1, p++;
  945. while(p < csiescseq.buf+csiescseq.len) {
  946. while(isdigit(*p)) {
  947. csiescseq.arg[csiescseq.narg] *= 10;
  948. csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
  949. }
  950. if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
  951. csiescseq.narg++, p++;
  952. else {
  953. csiescseq.mode = *p;
  954. csiescseq.narg++;
  955. return;
  956. }
  957. }
  958. }
  959. void
  960. tmoveto(int x, int y) {
  961. LIMIT(x, 0, term.col-1);
  962. LIMIT(y, 0, term.row-1);
  963. term.c.state &= ~CURSOR_WRAPNEXT;
  964. term.c.x = x;
  965. term.c.y = y;
  966. }
  967. void
  968. tsetchar(char *c) {
  969. /*
  970. * The table is proudly stolen from rxvt.
  971. */
  972. if(term.c.attr.mode & ATTR_GFX) {
  973. char *vt100_0[62] = { /* 0x41 - 0x7e */
  974. "", "", "", "", "", "", "", /* A - G */
  975. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  976. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  977. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  978. "", "", "", "", "", "", "°", "±", /* ` - g */
  979. "", "", "", "", "", "", "", "", /* h - o */
  980. "", "", "", "", "", "", "", "", /* p - w */
  981. "", "", "", "π", "", "£", "·", /* x - ~ */
  982. };
  983. if(c[0] >= 0x41 && c[0] <= 0x7e
  984. && vt100_0[c[0] - 0x41]) {
  985. c = vt100_0[c[0] - 0x41];
  986. }
  987. }
  988. term.dirty[term.c.y] = 1;
  989. term.line[term.c.y][term.c.x] = term.c.attr;
  990. memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
  991. term.line[term.c.y][term.c.x].state |= GLYPH_SET;
  992. }
  993. void
  994. tclearregion(int x1, int y1, int x2, int y2) {
  995. int x, y, temp;
  996. if(x1 > x2)
  997. temp = x1, x1 = x2, x2 = temp;
  998. if(y1 > y2)
  999. temp = y1, y1 = y2, y2 = temp;
  1000. LIMIT(x1, 0, term.col-1);
  1001. LIMIT(x2, 0, term.col-1);
  1002. LIMIT(y1, 0, term.row-1);
  1003. LIMIT(y2, 0, term.row-1);
  1004. for(y = y1; y <= y2; y++) {
  1005. term.dirty[y] = 1;
  1006. for(x = x1; x <= x2; x++)
  1007. term.line[y][x].state = 0;
  1008. }
  1009. }
  1010. void
  1011. tdeletechar(int n) {
  1012. int src = term.c.x + n;
  1013. int dst = term.c.x;
  1014. int size = term.col - src;
  1015. term.dirty[term.c.y] = 1;
  1016. if(src >= term.col) {
  1017. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1018. return;
  1019. }
  1020. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  1021. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1022. }
  1023. void
  1024. tinsertblank(int n) {
  1025. int src = term.c.x;
  1026. int dst = src + n;
  1027. int size = term.col - dst;
  1028. term.dirty[term.c.y] = 1;
  1029. if(dst >= term.col) {
  1030. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1031. return;
  1032. }
  1033. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  1034. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1035. }
  1036. void
  1037. tinsertblankline(int n) {
  1038. if(term.c.y < term.top || term.c.y > term.bot)
  1039. return;
  1040. tscrolldown(term.c.y, n);
  1041. }
  1042. void
  1043. tdeleteline(int n) {
  1044. if(term.c.y < term.top || term.c.y > term.bot)
  1045. return;
  1046. tscrollup(term.c.y, n);
  1047. }
  1048. void
  1049. tsetattr(int *attr, int l) {
  1050. int i;
  1051. for(i = 0; i < l; i++) {
  1052. switch(attr[i]) {
  1053. case 0:
  1054. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
  1055. | ATTR_ITALIC | ATTR_BLINK);
  1056. term.c.attr.fg = DefaultFG;
  1057. term.c.attr.bg = DefaultBG;
  1058. break;
  1059. case 1:
  1060. term.c.attr.mode |= ATTR_BOLD;
  1061. break;
  1062. case 3: /* enter standout (highlight) */
  1063. term.c.attr.mode |= ATTR_ITALIC;
  1064. break;
  1065. case 4:
  1066. term.c.attr.mode |= ATTR_UNDERLINE;
  1067. break;
  1068. case 5:
  1069. term.c.attr.mode |= ATTR_BLINK;
  1070. break;
  1071. case 7:
  1072. term.c.attr.mode |= ATTR_REVERSE;
  1073. break;
  1074. case 21:
  1075. case 22:
  1076. term.c.attr.mode &= ~ATTR_BOLD;
  1077. break;
  1078. case 23: /* leave standout (highlight) mode */
  1079. term.c.attr.mode &= ~ATTR_ITALIC;
  1080. break;
  1081. case 24:
  1082. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1083. break;
  1084. case 25:
  1085. term.c.attr.mode &= ~ATTR_BLINK;
  1086. break;
  1087. case 27:
  1088. term.c.attr.mode &= ~ATTR_REVERSE;
  1089. break;
  1090. case 38:
  1091. if(i + 2 < l && attr[i + 1] == 5) {
  1092. i += 2;
  1093. if(BETWEEN(attr[i], 0, 255))
  1094. term.c.attr.fg = attr[i];
  1095. else
  1096. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
  1097. }
  1098. else
  1099. fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
  1100. break;
  1101. case 39:
  1102. term.c.attr.fg = DefaultFG;
  1103. break;
  1104. case 48:
  1105. if(i + 2 < l && attr[i + 1] == 5) {
  1106. i += 2;
  1107. if(BETWEEN(attr[i], 0, 255))
  1108. term.c.attr.bg = attr[i];
  1109. else
  1110. fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
  1111. }
  1112. else
  1113. fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
  1114. break;
  1115. case 49:
  1116. term.c.attr.bg = DefaultBG;
  1117. break;
  1118. default:
  1119. if(BETWEEN(attr[i], 30, 37))
  1120. term.c.attr.fg = attr[i] - 30;
  1121. else if(BETWEEN(attr[i], 40, 47))
  1122. term.c.attr.bg = attr[i] - 40;
  1123. else if(BETWEEN(attr[i], 90, 97))
  1124. term.c.attr.fg = attr[i] - 90 + 8;
  1125. else if(BETWEEN(attr[i], 100, 107))
  1126. term.c.attr.bg = attr[i] - 100 + 8;
  1127. else
  1128. fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
  1129. break;
  1130. }
  1131. }
  1132. }
  1133. void
  1134. tsetscroll(int t, int b) {
  1135. int temp;
  1136. LIMIT(t, 0, term.row-1);
  1137. LIMIT(b, 0, term.row-1);
  1138. if(t > b) {
  1139. temp = t;
  1140. t = b;
  1141. b = temp;
  1142. }
  1143. term.top = t;
  1144. term.bot = b;
  1145. }
  1146. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1147. void
  1148. tsetmode(bool priv, bool set, int *args, int narg) {
  1149. int *lim, mode;
  1150. for(lim = args + narg; args < lim; ++args) {
  1151. if(priv) {
  1152. switch(*args) {
  1153. break;
  1154. case 1: /* DECCKM -- Cursor key */
  1155. MODBIT(term.mode, set, MODE_APPKEYPAD);
  1156. break;
  1157. case 5: /* DECSCNM -- Reverve video */
  1158. mode = term.mode;
  1159. MODBIT(term.mode,set, MODE_REVERSE);
  1160. if(mode != term.mode)
  1161. redraw();
  1162. break;
  1163. case 6: /* XXX: DECOM -- Origin */
  1164. break;
  1165. case 7: /* DECAWM -- Auto wrap */
  1166. MODBIT(term.mode, set, MODE_WRAP);
  1167. break;
  1168. case 8: /* XXX: DECARM -- Auto repeat */
  1169. break;
  1170. case 0: /* Error (IGNORED) */
  1171. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1172. break;
  1173. case 25:
  1174. MODBIT(term.c.state, !set, CURSOR_HIDE);
  1175. break;
  1176. case 1000: /* 1000,1002: enable xterm mouse report */
  1177. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1178. break;
  1179. case 1002:
  1180. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1181. break;
  1182. case 1049: /* = 1047 and 1048 */
  1183. case 47:
  1184. case 1047:
  1185. if(IS_SET(MODE_ALTSCREEN))
  1186. tclearregion(0, 0, term.col-1, term.row-1);
  1187. if((set && !IS_SET(MODE_ALTSCREEN)) ||
  1188. (!set && IS_SET(MODE_ALTSCREEN))) {
  1189. tswapscreen();
  1190. }
  1191. if(*args != 1049)
  1192. break;
  1193. /* pass through */
  1194. case 1048:
  1195. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1196. break;
  1197. default:
  1198. /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
  1199. /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
  1200. /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
  1201. /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
  1202. /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
  1203. /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
  1204. fprintf(stderr,
  1205. "erresc: unknown private set/reset mode %d\n",
  1206. *args);
  1207. break;
  1208. }
  1209. } else {
  1210. switch(*args) {
  1211. case 0: /* Error (IGNORED) */
  1212. break;
  1213. case 2: /* KAM -- keyboard action */
  1214. MODBIT(term.mode, set, MODE_KBDLOCK);
  1215. break;
  1216. case 4: /* IRM -- Insertion-replacement */
  1217. MODBIT(term.mode, set, MODE_INSERT);
  1218. break;
  1219. case 12: /* XXX: SRM -- Send/Receive */
  1220. break;
  1221. case 20: /* LNM -- Linefeed/new line */
  1222. MODBIT(term.mode, set, MODE_CRLF);
  1223. break;
  1224. default:
  1225. fprintf(stderr,
  1226. "erresc: unknown set/reset mode %d\n",
  1227. *args);
  1228. break;
  1229. }
  1230. }
  1231. }
  1232. }
  1233. #undef MODBIT
  1234. void
  1235. csihandle(void) {
  1236. switch(csiescseq.mode) {
  1237. default:
  1238. unknown:
  1239. fprintf(stderr, "erresc: unknown csi ");
  1240. csidump();
  1241. /* die(""); */
  1242. break;
  1243. case '@': /* ICH -- Insert <n> blank char */
  1244. DEFAULT(csiescseq.arg[0], 1);
  1245. tinsertblank(csiescseq.arg[0]);
  1246. break;
  1247. case 'A': /* CUU -- Cursor <n> Up */
  1248. case 'e':
  1249. DEFAULT(csiescseq.arg[0], 1);
  1250. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1251. break;
  1252. case 'B': /* CUD -- Cursor <n> Down */
  1253. DEFAULT(csiescseq.arg[0], 1);
  1254. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1255. break;
  1256. case 'C': /* CUF -- Cursor <n> Forward */
  1257. case 'a':
  1258. DEFAULT(csiescseq.arg[0], 1);
  1259. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1260. break;
  1261. case 'D': /* CUB -- Cursor <n> Backward */
  1262. DEFAULT(csiescseq.arg[0], 1);
  1263. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1264. break;
  1265. case 'E': /* CNL -- Cursor <n> Down and first col */
  1266. DEFAULT(csiescseq.arg[0], 1);
  1267. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1268. break;
  1269. case 'F': /* CPL -- Cursor <n> Up and first col */
  1270. DEFAULT(csiescseq.arg[0], 1);
  1271. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1272. break;
  1273. case 'g': /* TBC -- Tabulation clear */
  1274. switch (csiescseq.arg[0]) {
  1275. case 0: /* clear current tab stop */
  1276. term.tabs[term.c.x] = 0;
  1277. break;
  1278. case 3: /* clear all the tabs */
  1279. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1280. break;
  1281. default:
  1282. goto unknown;
  1283. }
  1284. break;
  1285. case 'G': /* CHA -- Move to <col> */
  1286. case '`': /* HPA */
  1287. DEFAULT(csiescseq.arg[0], 1);
  1288. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1289. break;
  1290. case 'H': /* CUP -- Move to <row> <col> */
  1291. case 'f': /* HVP */
  1292. DEFAULT(csiescseq.arg[0], 1);
  1293. DEFAULT(csiescseq.arg[1], 1);
  1294. tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1295. break;
  1296. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1297. DEFAULT(csiescseq.arg[0], 1);
  1298. while(csiescseq.arg[0]--)
  1299. tputtab(1);
  1300. break;
  1301. case 'J': /* ED -- Clear screen */
  1302. sel.bx = -1;
  1303. switch(csiescseq.arg[0]) {
  1304. case 0: /* below */
  1305. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1306. if(term.c.y < term.row-1)
  1307. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  1308. break;
  1309. case 1: /* above */
  1310. if(term.c.y > 1)
  1311. tclearregion(0, 0, term.col-1, term.c.y-1);
  1312. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1313. break;
  1314. case 2: /* all */
  1315. tclearregion(0, 0, term.col-1, term.row-1);
  1316. break;
  1317. default:
  1318. goto unknown;
  1319. }
  1320. break;
  1321. case 'K': /* EL -- Clear line */
  1322. switch(csiescseq.arg[0]) {
  1323. case 0: /* right */
  1324. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1325. break;
  1326. case 1: /* left */
  1327. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1328. break;
  1329. case 2: /* all */
  1330. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1331. break;
  1332. }
  1333. break;
  1334. case 'S': /* SU -- Scroll <n> line up */
  1335. DEFAULT(csiescseq.arg[0], 1);
  1336. tscrollup(term.top, csiescseq.arg[0]);
  1337. break;
  1338. case 'T': /* SD -- Scroll <n> line down */
  1339. DEFAULT(csiescseq.arg[0], 1);
  1340. tscrolldown(term.top, csiescseq.arg[0]);
  1341. break;
  1342. case 'L': /* IL -- Insert <n> blank lines */
  1343. DEFAULT(csiescseq.arg[0], 1);
  1344. tinsertblankline(csiescseq.arg[0]);
  1345. break;
  1346. case 'l': /* RM -- Reset Mode */
  1347. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1348. break;
  1349. case 'M': /* DL -- Delete <n> lines */
  1350. DEFAULT(csiescseq.arg[0], 1);
  1351. tdeleteline(csiescseq.arg[0]);
  1352. break;
  1353. case 'X': /* ECH -- Erase <n> char */
  1354. DEFAULT(csiescseq.arg[0], 1);
  1355. tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
  1356. break;
  1357. case 'P': /* DCH -- Delete <n> char */
  1358. DEFAULT(csiescseq.arg[0], 1);
  1359. tdeletechar(csiescseq.arg[0]);
  1360. break;
  1361. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1362. DEFAULT(csiescseq.arg[0], 1);
  1363. while(csiescseq.arg[0]--)
  1364. tputtab(0);
  1365. break;
  1366. case 'd': /* VPA -- Move to <row> */
  1367. DEFAULT(csiescseq.arg[0], 1);
  1368. tmoveto(term.c.x, csiescseq.arg[0]-1);
  1369. break;
  1370. case 'h': /* SM -- Set terminal mode */
  1371. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1372. break;
  1373. case 'm': /* SGR -- Terminal attribute (color) */
  1374. tsetattr(csiescseq.arg, csiescseq.narg);
  1375. break;
  1376. case 'r': /* DECSTBM -- Set Scrolling Region */
  1377. if(csiescseq.priv)
  1378. goto unknown;
  1379. else {
  1380. DEFAULT(csiescseq.arg[0], 1);
  1381. DEFAULT(csiescseq.arg[1], term.row);
  1382. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1383. tmoveto(0, 0);
  1384. }
  1385. break;
  1386. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1387. tcursor(CURSOR_SAVE);
  1388. break;
  1389. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1390. tcursor(CURSOR_LOAD);
  1391. break;
  1392. }
  1393. }
  1394. void
  1395. csidump(void) {
  1396. int i;
  1397. printf("ESC[");
  1398. for(i = 0; i < csiescseq.len; i++) {
  1399. uint c = csiescseq.buf[i] & 0xff;
  1400. if(isprint(c)) putchar(c);
  1401. else if(c == '\n') printf("(\\n)");
  1402. else if(c == '\r') printf("(\\r)");
  1403. else if(c == 0x1b) printf("(\\e)");
  1404. else printf("(%02x)", c);
  1405. }
  1406. putchar('\n');
  1407. }
  1408. void
  1409. csireset(void) {
  1410. memset(&csiescseq, 0, sizeof(csiescseq));
  1411. }
  1412. void
  1413. strhandle(void) {
  1414. char *p;
  1415. /*
  1416. * TODO: make this being useful in case of color palette change.
  1417. */
  1418. strparse();
  1419. p = strescseq.buf;
  1420. switch(strescseq.type) {
  1421. case ']': /* OSC -- Operating System Command */
  1422. switch(p[0]) {
  1423. case '0':
  1424. case '1':
  1425. case '2':
  1426. /*
  1427. * TODO: Handle special chars in string, like umlauts.
  1428. */
  1429. if(p[1] == ';') {
  1430. XStoreName(xw.dpy, xw.win, strescseq.buf+2);
  1431. }
  1432. break;
  1433. case ';':
  1434. XStoreName(xw.dpy, xw.win, strescseq.buf+1);
  1435. break;
  1436. case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
  1437. break;
  1438. default:
  1439. fprintf(stderr, "erresc: unknown str ");
  1440. strdump();
  1441. break;
  1442. }
  1443. break;
  1444. case 'k': /* old title set compatibility */
  1445. XStoreName(xw.dpy, xw.win, strescseq.buf);
  1446. break;
  1447. case 'P': /* DSC -- Device Control String */
  1448. case '_': /* APC -- Application Program Command */
  1449. case '^': /* PM -- Privacy Message */
  1450. default:
  1451. fprintf(stderr, "erresc: unknown str ");
  1452. strdump();
  1453. /* die(""); */
  1454. break;
  1455. }
  1456. }
  1457. void
  1458. strparse(void) {
  1459. /*
  1460. * TODO: Implement parsing like for CSI when required.
  1461. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1462. */
  1463. return;
  1464. }
  1465. void
  1466. strdump(void) {
  1467. int i;
  1468. printf("ESC%c", strescseq.type);
  1469. for(i = 0; i < strescseq.len; i++) {
  1470. uint c = strescseq.buf[i] & 0xff;
  1471. if(isprint(c)) putchar(c);
  1472. else if(c == '\n') printf("(\\n)");
  1473. else if(c == '\r') printf("(\\r)");
  1474. else if(c == 0x1b) printf("(\\e)");
  1475. else printf("(%02x)", c);
  1476. }
  1477. printf("ESC\\\n");
  1478. }
  1479. void
  1480. strreset(void) {
  1481. memset(&strescseq, 0, sizeof(strescseq));
  1482. }
  1483. void
  1484. tputtab(bool forward) {
  1485. uint x = term.c.x;
  1486. if(forward) {
  1487. if(x == term.col)
  1488. return;
  1489. for(++x; x < term.col && !term.tabs[x]; ++x)
  1490. /* nothing */ ;
  1491. } else {
  1492. if(x == 0)
  1493. return;
  1494. for(--x; x > 0 && !term.tabs[x]; --x)
  1495. /* nothing */ ;
  1496. }
  1497. tmoveto(x, term.c.y);
  1498. }
  1499. void
  1500. tputc(char *c, int len) {
  1501. uchar ascii = *c;
  1502. if(iofd != -1)
  1503. write(iofd, c, len);
  1504. switch(ascii) {
  1505. case '\t':
  1506. tputtab(1);
  1507. return;
  1508. case '\b':
  1509. tmoveto(term.c.x-1, term.c.y);
  1510. return;
  1511. case '\r':
  1512. tmoveto(0, term.c.y);
  1513. return;
  1514. case '\f':
  1515. case '\v':
  1516. case '\n':
  1517. /* go to first col if the mode is set */
  1518. tnewline(IS_SET(MODE_CRLF));
  1519. return;
  1520. case '\a':
  1521. if(term.esc & ESC_STR)
  1522. break;
  1523. if(!(xw.state & WIN_FOCUSED))
  1524. xseturgency(1);
  1525. return;
  1526. case '\033':
  1527. csireset();
  1528. term.esc = ESC_START;
  1529. return;
  1530. }
  1531. if(term.esc & ESC_START) {
  1532. if(term.esc & ESC_CSI) {
  1533. csiescseq.buf[csiescseq.len++] = ascii;
  1534. if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
  1535. term.esc = 0;
  1536. csiparse(), csihandle();
  1537. }
  1538. } else if(term.esc & ESC_STR) {
  1539. switch(ascii) {
  1540. case '\033':
  1541. term.esc = ESC_START | ESC_STR_END;
  1542. break;
  1543. case '\a': /* backwards compatibility to xterm */
  1544. term.esc = 0;
  1545. strhandle();
  1546. break;
  1547. default:
  1548. strescseq.buf[strescseq.len++] = ascii;
  1549. if(strescseq.len+1 >= STR_BUF_SIZ) {
  1550. term.esc = 0;
  1551. strhandle();
  1552. }
  1553. }
  1554. } else if(term.esc & ESC_STR_END) {
  1555. term.esc = 0;
  1556. if(ascii == '\\')
  1557. strhandle();
  1558. } else if(term.esc & ESC_ALTCHARSET) {
  1559. switch(ascii) {
  1560. case '0': /* Line drawing set */
  1561. term.c.attr.mode |= ATTR_GFX;
  1562. break;
  1563. case 'B': /* USASCII */
  1564. term.c.attr.mode &= ~ATTR_GFX;
  1565. break;
  1566. case 'A': /* UK (IGNORED) */
  1567. case '<': /* multinational charset (IGNORED) */
  1568. case '5': /* Finnish (IGNORED) */
  1569. case 'C': /* Finnish (IGNORED) */
  1570. case 'K': /* German (IGNORED) */
  1571. break;
  1572. default:
  1573. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1574. }
  1575. term.esc = 0;
  1576. } else {
  1577. switch(ascii) {
  1578. case '[':
  1579. term.esc |= ESC_CSI;
  1580. break;
  1581. case 'P': /* DCS -- Device Control String */
  1582. case '_': /* APC -- Application Program Command */
  1583. case '^': /* PM -- Privacy Message */
  1584. case ']': /* OSC -- Operating System Command */
  1585. case 'k': /* old title set compatibility */
  1586. strreset();
  1587. strescseq.type = ascii;
  1588. term.esc |= ESC_STR;
  1589. break;
  1590. case '(': /* set primary charset G0 */
  1591. term.esc |= ESC_ALTCHARSET;
  1592. break;
  1593. case ')': /* set secondary charset G1 (IGNORED) */
  1594. case '*': /* set tertiary charset G2 (IGNORED) */
  1595. case '+': /* set quaternary charset G3 (IGNORED) */
  1596. term.esc = 0;
  1597. break;
  1598. case 'D': /* IND -- Linefeed */
  1599. if(term.c.y == term.bot)
  1600. tscrollup(term.top, 1);
  1601. else
  1602. tmoveto(term.c.x, term.c.y+1);
  1603. term.esc = 0;
  1604. break;
  1605. case 'E': /* NEL -- Next line */
  1606. tnewline(1); /* always go to first col */
  1607. term.esc = 0;
  1608. break;
  1609. case 'H': /* HTS -- Horizontal tab stop */
  1610. term.tabs[term.c.x] = 1;
  1611. term.esc = 0;
  1612. break;
  1613. case 'M': /* RI -- Reverse index */
  1614. if(term.c.y == term.top)
  1615. tscrolldown(term.top, 1);
  1616. else
  1617. tmoveto(term.c.x, term.c.y-1);
  1618. term.esc = 0;
  1619. break;
  1620. case 'c': /* RIS -- Reset to inital state */
  1621. treset();
  1622. term.esc = 0;
  1623. xclear(0, 0, xw.w, xw.h);
  1624. xresettitle();
  1625. break;
  1626. case '=': /* DECPAM -- Application keypad */
  1627. term.mode |= MODE_APPKEYPAD;
  1628. term.esc = 0;
  1629. break;
  1630. case '>': /* DECPNM -- Normal keypad */
  1631. term.mode &= ~MODE_APPKEYPAD;
  1632. term.esc = 0;
  1633. break;
  1634. case '7': /* DECSC -- Save Cursor */
  1635. tcursor(CURSOR_SAVE);
  1636. term.esc = 0;
  1637. break;
  1638. case '8': /* DECRC -- Restore Cursor */
  1639. tcursor(CURSOR_LOAD);
  1640. term.esc = 0;
  1641. break;
  1642. case '\\': /* ST -- Stop */
  1643. term.esc = 0;
  1644. break;
  1645. default:
  1646. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1647. (uchar) ascii, isprint(ascii)?ascii:'.');
  1648. term.esc = 0;
  1649. }
  1650. }
  1651. } else {
  1652. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1653. sel.bx = -1;
  1654. if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
  1655. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1656. tnewline(1); /* always go to first col */
  1657. tsetchar(c);
  1658. if(term.c.x+1 < term.col)
  1659. tmoveto(term.c.x+1, term.c.y);
  1660. else
  1661. term.c.state |= CURSOR_WRAPNEXT;
  1662. }
  1663. }
  1664. }
  1665. int
  1666. tresize(int col, int row) {
  1667. int i, x;
  1668. int minrow = MIN(row, term.row);
  1669. int mincol = MIN(col, term.col);
  1670. int slide = term.c.y - row + 1;
  1671. if(col < 1 || row < 1)
  1672. return 0;
  1673. /* free unneeded rows */
  1674. i = 0;
  1675. if(slide > 0) {
  1676. /* slide screen to keep cursor where we expect it -
  1677. * tscrollup would work here, but we can optimize to
  1678. * memmove because we're freeing the earlier lines */
  1679. for(/* i = 0 */; i < slide; i++) {
  1680. free(term.line[i]);
  1681. free(term.alt[i]);
  1682. }
  1683. memmove(term.line, term.line + slide, row * sizeof(Line));
  1684. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1685. }
  1686. for(i += row; i < term.row; i++) {
  1687. free(term.line[i]);
  1688. free(term.alt[i]);
  1689. }
  1690. /* resize to new height */
  1691. term.line = xrealloc(term.line, row * sizeof(Line));
  1692. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1693. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1694. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1695. /* resize each row to new width, zero-pad if needed */
  1696. for(i = 0; i < minrow; i++) {
  1697. term.dirty[i] = 1;
  1698. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1699. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1700. for(x = mincol; x < col; x++) {
  1701. term.line[i][x].state = 0;
  1702. term.alt[i][x].state = 0;
  1703. }
  1704. }
  1705. /* allocate any new rows */
  1706. for(/* i == minrow */; i < row; i++) {
  1707. term.dirty[i] = 1;
  1708. term.line[i] = xcalloc(col, sizeof(Glyph));
  1709. term.alt [i] = xcalloc(col, sizeof(Glyph));
  1710. }
  1711. if(col > term.col) {
  1712. bool *bp = term.tabs + term.col;
  1713. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1714. while(--bp > term.tabs && !*bp)
  1715. /* nothing */ ;
  1716. for(bp += TAB; bp < term.tabs + col; bp += TAB)
  1717. *bp = 1;
  1718. }
  1719. /* update terminal size */
  1720. term.col = col, term.row = row;
  1721. /* make use of the LIMIT in tmoveto */
  1722. tmoveto(term.c.x, term.c.y);
  1723. /* reset scrolling region */
  1724. tsetscroll(0, row-1);
  1725. return (slide > 0);
  1726. }
  1727. void
  1728. xresize(int col, int row) {
  1729. xw.tw = MAX(1, 2*BORDER + col * xw.cw);
  1730. xw.th = MAX(1, 2*BORDER + row * xw.ch);
  1731. XftDrawChange(xw.xft_draw, xw.buf);
  1732. }
  1733. void
  1734. xloadcols(void) {
  1735. int i, r, g, b;
  1736. XRenderColor xft_color = { .alpha = 0 };
  1737. ulong white = WhitePixel(xw.dpy, xw.scr);
  1738. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1739. for(i = 0; i < LEN(colorname); i++) {
  1740. if(!colorname[i])
  1741. continue;
  1742. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
  1743. dc.col[i] = white;
  1744. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1745. } else
  1746. dc.col[i] = dc.xft_col[i].pixel;
  1747. }
  1748. /* load colors [16-255] ; same colors as xterm */
  1749. for(i = 16, r = 0; r < 6; r++)
  1750. for(g = 0; g < 6; g++)
  1751. for(b = 0; b < 6; b++) {
  1752. xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1753. xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1754. xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1755. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
  1756. dc.col[i] = white;
  1757. fprintf(stderr, "Could not allocate color %d\n", i);
  1758. } else
  1759. dc.col[i] = dc.xft_col[i].pixel;
  1760. i++;
  1761. }
  1762. for(r = 0; r < 24; r++, i++) {
  1763. xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
  1764. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
  1765. dc.col[i] = white;
  1766. fprintf(stderr, "Could not allocate color %d\n", i);
  1767. } else
  1768. dc.col[i] = dc.xft_col[i].pixel;
  1769. }
  1770. }
  1771. void
  1772. xclear(int x1, int y1, int x2, int y2) {
  1773. XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
  1774. XFillRectangle(xw.dpy, xw.buf, dc.gc,
  1775. BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
  1776. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1777. }
  1778. void
  1779. xhints(void) {
  1780. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1781. XWMHints wm = {.flags = InputHint, .input = 1};
  1782. XSizeHints *sizeh = NULL;
  1783. sizeh = XAllocSizeHints();
  1784. if(xw.isfixed == False) {
  1785. sizeh->flags = PSize | PResizeInc | PBaseSize;
  1786. sizeh->height = xw.h;
  1787. sizeh->width = xw.w;
  1788. sizeh->height_inc = xw.ch;
  1789. sizeh->width_inc = xw.cw;
  1790. sizeh->base_height = 2*BORDER;
  1791. sizeh->base_width = 2*BORDER;
  1792. } else {
  1793. sizeh->flags = PMaxSize | PMinSize;
  1794. sizeh->min_width = sizeh->max_width = xw.fw;
  1795. sizeh->min_height = sizeh->max_height = xw.fh;
  1796. }
  1797. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  1798. XFree(sizeh);
  1799. }
  1800. void
  1801. xinitfont(Font *f, char *fontstr) {
  1802. f->xft_set = XftFontOpenName(xw.dpy, xw.scr, fontstr);
  1803. if(!f->xft_set)
  1804. die("st: can't open font %s.\n", fontstr);
  1805. f->ascent = f->xft_set->ascent;
  1806. f->descent = f->xft_set->descent;
  1807. f->lbearing = 0;
  1808. f->rbearing = f->xft_set->max_advance_width;
  1809. }
  1810. void
  1811. initfonts(char *fontstr, char *bfontstr, char *ifontstr, char *ibfontstr) {
  1812. xinitfont(&dc.font, fontstr);
  1813. xinitfont(&dc.bfont, bfontstr);
  1814. xinitfont(&dc.ifont, ifontstr);
  1815. xinitfont(&dc.ibfont, ibfontstr);
  1816. }
  1817. void
  1818. xinit(void) {
  1819. XSetWindowAttributes attrs;
  1820. Cursor cursor;
  1821. Window parent;
  1822. int sw, sh, major, minor;
  1823. if(!(xw.dpy = XOpenDisplay(NULL)))
  1824. die("Can't open display\n");
  1825. xw.scr = XDefaultScreen(xw.dpy);
  1826. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  1827. /* font */
  1828. initfonts(FONT, BOLDFONT, ITALICFONT, ITALICBOLDFONT);
  1829. /* XXX: Assuming same size for bold font */
  1830. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1831. xw.ch = dc.font.ascent + dc.font.descent;
  1832. /* colors */
  1833. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1834. xloadcols();
  1835. /* adjust fixed window geometry */
  1836. if(xw.isfixed) {
  1837. sw = DisplayWidth(xw.dpy, xw.scr);
  1838. sh = DisplayHeight(xw.dpy, xw.scr);
  1839. if(xw.fx < 0)
  1840. xw.fx = sw + xw.fx - xw.fw - 1;
  1841. if(xw.fy < 0)
  1842. xw.fy = sh + xw.fy - xw.fh - 1;
  1843. xw.h = xw.fh;
  1844. xw.w = xw.fw;
  1845. } else {
  1846. /* window - default size */
  1847. xw.h = 2*BORDER + term.row * xw.ch;
  1848. xw.w = 2*BORDER + term.col * xw.cw;
  1849. xw.fx = 0;
  1850. xw.fy = 0;
  1851. }
  1852. attrs.background_pixel = dc.col[DefaultBG];
  1853. attrs.border_pixel = dc.col[DefaultBG];
  1854. attrs.bit_gravity = NorthWestGravity;
  1855. attrs.event_mask = FocusChangeMask | KeyPressMask
  1856. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1857. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  1858. attrs.colormap = xw.cmap;
  1859. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  1860. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  1861. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1862. xw.vis,
  1863. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1864. | CWColormap,
  1865. &attrs);
  1866. /* double buffering */
  1867. if(!XdbeQueryExtension(xw.dpy, &major, &minor))
  1868. die("Xdbe extension is not present\n");
  1869. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  1870. /* Xft rendering context */
  1871. xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  1872. /* input methods */
  1873. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1874. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1875. | XIMStatusNothing, XNClientWindow, xw.win,
  1876. XNFocusWindow, xw.win, NULL);
  1877. /* gc */
  1878. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1879. /* white cursor, black outline */
  1880. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1881. XDefineCursor(xw.dpy, xw.win, cursor);
  1882. XRecolorCursor(xw.dpy, cursor,
  1883. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1884. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1885. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1886. xresettitle();
  1887. XMapWindow(xw.dpy, xw.win);
  1888. xhints();
  1889. XSync(xw.dpy, 0);
  1890. }
  1891. void
  1892. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1893. int fg = base.fg, bg = base.bg, temp;
  1894. int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1895. Font *font = &dc.font;
  1896. XGlyphInfo extents;
  1897. /* only switch default fg/bg if term is in RV mode */
  1898. if(IS_SET(MODE_REVERSE)) {
  1899. if(fg == DefaultFG)
  1900. fg = DefaultBG;
  1901. if(bg == DefaultBG)
  1902. bg = DefaultFG;
  1903. }
  1904. if(base.mode & ATTR_REVERSE)
  1905. temp = fg, fg = bg, bg = temp;
  1906. if(base.mode & ATTR_BOLD) {
  1907. fg += 8;
  1908. font = &dc.bfont;
  1909. }
  1910. if(base.mode & ATTR_ITALIC)
  1911. font = &dc.ifont;
  1912. if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
  1913. font = &dc.ibfont;
  1914. XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
  1915. XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
  1916. XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen, &extents);
  1917. width = extents.xOff;
  1918. XftDrawRect(xw.xft_draw, &dc.xft_col[bg], winx, winy - font->ascent, width, xw.ch);
  1919. XftDrawStringUtf8(xw.xft_draw, &dc.xft_col[fg], font->xft_set, winx, winy, (FcChar8 *)s, bytelen);
  1920. if(base.mode & ATTR_UNDERLINE)
  1921. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1922. }
  1923. void
  1924. xdrawcursor(void) {
  1925. static int oldx = 0;
  1926. static int oldy = 0;
  1927. int sl;
  1928. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1929. LIMIT(oldx, 0, term.col-1);
  1930. LIMIT(oldy, 0, term.row-1);
  1931. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1932. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1933. /* remove the old cursor */
  1934. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1935. sl = utf8size(term.line[oldy][oldx].c);
  1936. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1937. } else
  1938. xclear(oldx, oldy, oldx, oldy);
  1939. /* draw the new one */
  1940. if(!(term.c.state & CURSOR_HIDE)) {
  1941. if(!(xw.state & WIN_FOCUSED))
  1942. g.bg = DefaultUCS;
  1943. if(IS_SET(MODE_REVERSE))
  1944. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  1945. sl = utf8size(g.c);
  1946. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1947. oldx = term.c.x, oldy = term.c.y;
  1948. }
  1949. }
  1950. void
  1951. xresettitle(void) {
  1952. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1953. }
  1954. void
  1955. redraw(void) {
  1956. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  1957. xclear(0, 0, xw.w, xw.h);
  1958. tfulldirt();
  1959. draw();
  1960. XSync(xw.dpy, False); /* necessary for a good tput flash */
  1961. nanosleep(&tv, NULL);
  1962. }
  1963. void
  1964. draw() {
  1965. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  1966. drawregion(0, 0, term.col, term.row);
  1967. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  1968. }
  1969. void
  1970. drawregion(int x1, int y1, int x2, int y2) {
  1971. int ic, ib, x, y, ox, sl;
  1972. Glyph base, new;
  1973. char buf[DRAW_BUF_SIZ];
  1974. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
  1975. if((sel.alt && !alt) || (!sel.alt && alt))
  1976. ena_sel = 0;
  1977. if(!(xw.state & WIN_VISIBLE))
  1978. return;
  1979. for(y = y1; y < y2; y++) {
  1980. if(!term.dirty[y])
  1981. continue;
  1982. xclear(0, y, term.col, y);
  1983. term.dirty[y] = 0;
  1984. base = term.line[y][0];
  1985. ic = ib = ox = 0;
  1986. for(x = x1; x < x2; x++) {
  1987. new = term.line[y][x];
  1988. if(ena_sel && *(new.c) && selected(x, y))
  1989. new.mode ^= ATTR_REVERSE;
  1990. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1991. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1992. xdraws(buf, base, ox, y, ic, ib);
  1993. ic = ib = 0;
  1994. }
  1995. if(new.state & GLYPH_SET) {
  1996. if(ib == 0) {
  1997. ox = x;
  1998. base = new;
  1999. }
  2000. sl = utf8size(new.c);
  2001. memcpy(buf+ib, new.c, sl);
  2002. ib += sl;
  2003. ++ic;
  2004. }
  2005. }
  2006. if(ib > 0)
  2007. xdraws(buf, base, ox, y, ic, ib);
  2008. }
  2009. xdrawcursor();
  2010. }
  2011. void
  2012. expose(XEvent *ev) {
  2013. XExposeEvent *e = &ev->xexpose;
  2014. if(xw.state & WIN_REDRAW) {
  2015. if(!e->count)
  2016. xw.state &= ~WIN_REDRAW;
  2017. }
  2018. }
  2019. void
  2020. visibility(XEvent *ev) {
  2021. XVisibilityEvent *e = &ev->xvisibility;
  2022. if(e->state == VisibilityFullyObscured)
  2023. xw.state &= ~WIN_VISIBLE;
  2024. else if(!(xw.state & WIN_VISIBLE))
  2025. /* need a full redraw for next Expose, not just a buf copy */
  2026. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2027. }
  2028. void
  2029. unmap(XEvent *ev) {
  2030. xw.state &= ~WIN_VISIBLE;
  2031. }
  2032. void
  2033. xseturgency(int add) {
  2034. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2035. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2036. XSetWMHints(xw.dpy, xw.win, h);
  2037. XFree(h);
  2038. }
  2039. void
  2040. focus(XEvent *ev) {
  2041. if(ev->type == FocusIn) {
  2042. xw.state |= WIN_FOCUSED;
  2043. xseturgency(0);
  2044. } else
  2045. xw.state &= ~WIN_FOCUSED;
  2046. }
  2047. char*
  2048. kmap(KeySym k, uint state) {
  2049. int i;
  2050. state &= ~Mod2Mask;
  2051. for(i = 0; i < LEN(key); i++) {
  2052. uint mask = key[i].mask;
  2053. if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
  2054. return (char*)key[i].s;
  2055. }
  2056. return NULL;
  2057. }
  2058. void
  2059. kpress(XEvent *ev) {
  2060. XKeyEvent *e = &ev->xkey;
  2061. KeySym ksym;
  2062. char buf[32];
  2063. char *customkey;
  2064. int len;
  2065. int meta;
  2066. int shift;
  2067. Status status;
  2068. if (IS_SET(MODE_KBDLOCK))
  2069. return;
  2070. meta = e->state & Mod1Mask;
  2071. shift = e->state & ShiftMask;
  2072. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  2073. /* 1. custom keys from config.h */
  2074. if((customkey = kmap(ksym, e->state)))
  2075. ttywrite(customkey, strlen(customkey));
  2076. /* 2. hardcoded (overrides X lookup) */
  2077. else
  2078. switch(ksym) {
  2079. case XK_Up:
  2080. case XK_Down:
  2081. case XK_Left:
  2082. case XK_Right:
  2083. /* XXX: shift up/down doesn't work */
  2084. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
  2085. ttywrite(buf, 3);
  2086. break;
  2087. case XK_Insert:
  2088. if(shift)
  2089. selpaste();
  2090. break;
  2091. case XK_Return:
  2092. if(IS_SET(MODE_CRLF))
  2093. ttywrite("\r\n", 2);
  2094. else
  2095. ttywrite("\r", 1);
  2096. break;
  2097. /* 3. X lookup */
  2098. default:
  2099. if(len > 0) {
  2100. if(meta && len == 1)
  2101. ttywrite("\033", 1);
  2102. ttywrite(buf, len);
  2103. }
  2104. break;
  2105. }
  2106. }
  2107. void
  2108. cmessage(XEvent *e) {
  2109. /* See xembed specs
  2110. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2111. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2112. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2113. xw.state |= WIN_FOCUSED;
  2114. xseturgency(0);
  2115. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2116. xw.state &= ~WIN_FOCUSED;
  2117. }
  2118. }
  2119. }
  2120. void
  2121. resize(XEvent *e) {
  2122. int col, row;
  2123. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2124. return;
  2125. xw.w = e->xconfigure.width;
  2126. xw.h = e->xconfigure.height;
  2127. col = (xw.w - 2*BORDER) / xw.cw;
  2128. row = (xw.h - 2*BORDER) / xw.ch;
  2129. if(col == term.col && row == term.row)
  2130. return;
  2131. xclear(0, 0, xw.w, xw.h);
  2132. tresize(col, row);
  2133. xresize(col, row);
  2134. ttyresize();
  2135. }
  2136. void
  2137. run(void) {
  2138. XEvent ev;
  2139. fd_set rfd;
  2140. int xfd = XConnectionNumber(xw.dpy), i;
  2141. struct timeval drawtimeout, *tv = NULL;
  2142. for(i = 0;; i++) {
  2143. FD_ZERO(&rfd);
  2144. FD_SET(cmdfd, &rfd);
  2145. FD_SET(xfd, &rfd);
  2146. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  2147. if(errno == EINTR)
  2148. continue;
  2149. die("select failed: %s\n", SERRNO);
  2150. }
  2151. /*
  2152. * Stop after a certain number of reads so the user does not
  2153. * feel like the system is stuttering.
  2154. */
  2155. if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
  2156. ttyread();
  2157. /*
  2158. * Just wait a bit so it isn't disturbing the
  2159. * user and the system is able to write something.
  2160. */
  2161. drawtimeout.tv_sec = 0;
  2162. drawtimeout.tv_usec = 5;
  2163. tv = &drawtimeout;
  2164. continue;
  2165. }
  2166. i = 0;
  2167. tv = NULL;
  2168. while(XPending(xw.dpy)) {
  2169. XNextEvent(xw.dpy, &ev);
  2170. if(XFilterEvent(&ev, xw.win))
  2171. continue;
  2172. if(handler[ev.type])
  2173. (handler[ev.type])(&ev);
  2174. }
  2175. draw();
  2176. XFlush(xw.dpy);
  2177. }
  2178. }
  2179. int
  2180. main(int argc, char *argv[]) {
  2181. int i, bitm, xr, yr;
  2182. uint wr, hr;
  2183. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2184. xw.isfixed = False;
  2185. for(i = 1; i < argc; i++) {
  2186. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2187. case 't':
  2188. if(++i < argc) opt_title = argv[i];
  2189. break;
  2190. case 'c':
  2191. if(++i < argc) opt_class = argv[i];
  2192. break;
  2193. case 'w':
  2194. if(++i < argc) opt_embed = argv[i];
  2195. break;
  2196. case 'f':
  2197. if(++i < argc) opt_io = argv[i];
  2198. break;
  2199. case 'e':
  2200. /* eat every remaining arguments */
  2201. if(++i < argc) opt_cmd = &argv[i];
  2202. goto run;
  2203. case 'g':
  2204. if(++i >= argc)
  2205. break;
  2206. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2207. if(bitm & XValue)
  2208. xw.fx = xr;
  2209. if(bitm & YValue)
  2210. xw.fy = yr;
  2211. if(bitm & WidthValue)
  2212. xw.fw = (int)wr;
  2213. if(bitm & HeightValue)
  2214. xw.fh = (int)hr;
  2215. if(bitm & XNegative && xw.fx == 0)
  2216. xw.fx = -1;
  2217. if(bitm & XNegative && xw.fy == 0)
  2218. xw.fy = -1;
  2219. if(xw.fh != 0 && xw.fw != 0)
  2220. xw.isfixed = True;
  2221. break;
  2222. case 'v':
  2223. default:
  2224. die(USAGE);
  2225. }
  2226. }
  2227. run:
  2228. setlocale(LC_CTYPE, "");
  2229. tnew(80, 24);
  2230. ttynew();
  2231. xinit();
  2232. selinit();
  2233. run();
  2234. return 0;
  2235. }