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.

2488 lines
56 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
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*, 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(!(xw.state & WIN_FOCUSED))
  1522. xseturgency(1);
  1523. return;
  1524. case '\033':
  1525. csireset();
  1526. term.esc = ESC_START;
  1527. return;
  1528. }
  1529. if(term.esc & ESC_START) {
  1530. if(term.esc & ESC_CSI) {
  1531. csiescseq.buf[csiescseq.len++] = ascii;
  1532. if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
  1533. term.esc = 0;
  1534. csiparse(), csihandle();
  1535. }
  1536. } else if(term.esc & ESC_STR) {
  1537. switch(ascii) {
  1538. case '\033':
  1539. term.esc = ESC_START | ESC_STR_END;
  1540. break;
  1541. case '\a': /* backwards compatibility to xterm */
  1542. term.esc = 0;
  1543. strhandle();
  1544. break;
  1545. default:
  1546. strescseq.buf[strescseq.len++] = ascii;
  1547. if(strescseq.len+1 >= STR_BUF_SIZ) {
  1548. term.esc = 0;
  1549. strhandle();
  1550. }
  1551. }
  1552. } else if(term.esc & ESC_STR_END) {
  1553. term.esc = 0;
  1554. if(ascii == '\\')
  1555. strhandle();
  1556. } else if(term.esc & ESC_ALTCHARSET) {
  1557. switch(ascii) {
  1558. case '0': /* Line drawing set */
  1559. term.c.attr.mode |= ATTR_GFX;
  1560. break;
  1561. case 'B': /* USASCII */
  1562. term.c.attr.mode &= ~ATTR_GFX;
  1563. break;
  1564. case 'A': /* UK (IGNORED) */
  1565. case '<': /* multinational charset (IGNORED) */
  1566. case '5': /* Finnish (IGNORED) */
  1567. case 'C': /* Finnish (IGNORED) */
  1568. case 'K': /* German (IGNORED) */
  1569. break;
  1570. default:
  1571. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1572. }
  1573. term.esc = 0;
  1574. } else {
  1575. switch(ascii) {
  1576. case '[':
  1577. term.esc |= ESC_CSI;
  1578. break;
  1579. case 'P': /* DCS -- Device Control String */
  1580. case '_': /* APC -- Application Program Command */
  1581. case '^': /* PM -- Privacy Message */
  1582. case ']': /* OSC -- Operating System Command */
  1583. case 'k': /* old title set compatibility */
  1584. strreset();
  1585. strescseq.type = ascii;
  1586. term.esc |= ESC_STR;
  1587. break;
  1588. case '(': /* set primary charset G0 */
  1589. term.esc |= ESC_ALTCHARSET;
  1590. break;
  1591. case ')': /* set secondary charset G1 (IGNORED) */
  1592. case '*': /* set tertiary charset G2 (IGNORED) */
  1593. case '+': /* set quaternary charset G3 (IGNORED) */
  1594. term.esc = 0;
  1595. break;
  1596. case 'D': /* IND -- Linefeed */
  1597. if(term.c.y == term.bot)
  1598. tscrollup(term.top, 1);
  1599. else
  1600. tmoveto(term.c.x, term.c.y+1);
  1601. term.esc = 0;
  1602. break;
  1603. case 'E': /* NEL -- Next line */
  1604. tnewline(1); /* always go to first col */
  1605. term.esc = 0;
  1606. break;
  1607. case 'H': /* HTS -- Horizontal tab stop */
  1608. term.tabs[term.c.x] = 1;
  1609. term.esc = 0;
  1610. break;
  1611. case 'M': /* RI -- Reverse index */
  1612. if(term.c.y == term.top)
  1613. tscrolldown(term.top, 1);
  1614. else
  1615. tmoveto(term.c.x, term.c.y-1);
  1616. term.esc = 0;
  1617. break;
  1618. case 'c': /* RIS -- Reset to inital state */
  1619. treset();
  1620. term.esc = 0;
  1621. xclear(0, 0, xw.w, xw.h);
  1622. xresettitle();
  1623. break;
  1624. case '=': /* DECPAM -- Application keypad */
  1625. term.mode |= MODE_APPKEYPAD;
  1626. term.esc = 0;
  1627. break;
  1628. case '>': /* DECPNM -- Normal keypad */
  1629. term.mode &= ~MODE_APPKEYPAD;
  1630. term.esc = 0;
  1631. break;
  1632. case '7': /* DECSC -- Save Cursor */
  1633. tcursor(CURSOR_SAVE);
  1634. term.esc = 0;
  1635. break;
  1636. case '8': /* DECRC -- Restore Cursor */
  1637. tcursor(CURSOR_LOAD);
  1638. term.esc = 0;
  1639. break;
  1640. case '\\': /* ST -- Stop */
  1641. term.esc = 0;
  1642. break;
  1643. default:
  1644. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1645. (uchar) ascii, isprint(ascii)?ascii:'.');
  1646. term.esc = 0;
  1647. }
  1648. }
  1649. } else {
  1650. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1651. sel.bx = -1;
  1652. if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
  1653. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1654. tnewline(1); /* always go to first col */
  1655. tsetchar(c);
  1656. if(term.c.x+1 < term.col)
  1657. tmoveto(term.c.x+1, term.c.y);
  1658. else
  1659. term.c.state |= CURSOR_WRAPNEXT;
  1660. }
  1661. }
  1662. }
  1663. int
  1664. tresize(int col, int row) {
  1665. int i, x;
  1666. int minrow = MIN(row, term.row);
  1667. int mincol = MIN(col, term.col);
  1668. int slide = term.c.y - row + 1;
  1669. if(col < 1 || row < 1)
  1670. return 0;
  1671. /* free unneeded rows */
  1672. i = 0;
  1673. if(slide > 0) {
  1674. /* slide screen to keep cursor where we expect it -
  1675. * tscrollup would work here, but we can optimize to
  1676. * memmove because we're freeing the earlier lines */
  1677. for(/* i = 0 */; i < slide; i++) {
  1678. free(term.line[i]);
  1679. free(term.alt[i]);
  1680. }
  1681. memmove(term.line, term.line + slide, row * sizeof(Line));
  1682. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1683. }
  1684. for(i += row; i < term.row; i++) {
  1685. free(term.line[i]);
  1686. free(term.alt[i]);
  1687. }
  1688. /* resize to new height */
  1689. term.line = xrealloc(term.line, row * sizeof(Line));
  1690. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1691. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1692. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1693. /* resize each row to new width, zero-pad if needed */
  1694. for(i = 0; i < minrow; i++) {
  1695. term.dirty[i] = 1;
  1696. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1697. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1698. for(x = mincol; x < col; x++) {
  1699. term.line[i][x].state = 0;
  1700. term.alt[i][x].state = 0;
  1701. }
  1702. }
  1703. /* allocate any new rows */
  1704. for(/* i == minrow */; i < row; i++) {
  1705. term.dirty[i] = 1;
  1706. term.line[i] = xcalloc(col, sizeof(Glyph));
  1707. term.alt [i] = xcalloc(col, sizeof(Glyph));
  1708. }
  1709. if(col > term.col) {
  1710. bool *bp = term.tabs + term.col;
  1711. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1712. while(--bp > term.tabs && !*bp)
  1713. /* nothing */ ;
  1714. for(bp += TAB; bp < term.tabs + col; bp += TAB)
  1715. *bp = 1;
  1716. }
  1717. /* update terminal size */
  1718. term.col = col, term.row = row;
  1719. /* make use of the LIMIT in tmoveto */
  1720. tmoveto(term.c.x, term.c.y);
  1721. /* reset scrolling region */
  1722. tsetscroll(0, row-1);
  1723. return (slide > 0);
  1724. }
  1725. void
  1726. xresize(int col, int row) {
  1727. xw.tw = MAX(1, 2*BORDER + col * xw.cw);
  1728. xw.th = MAX(1, 2*BORDER + row * xw.ch);
  1729. XftDrawChange(xw.xft_draw, xw.buf);
  1730. }
  1731. void
  1732. xloadcols(void) {
  1733. int i, r, g, b;
  1734. XRenderColor xft_color = { .alpha = 0 };
  1735. ulong white = WhitePixel(xw.dpy, xw.scr);
  1736. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1737. for(i = 0; i < LEN(colorname); i++) {
  1738. if(!colorname[i])
  1739. continue;
  1740. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
  1741. dc.col[i] = white;
  1742. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1743. } else
  1744. dc.col[i] = dc.xft_col[i].pixel;
  1745. }
  1746. /* load colors [16-255] ; same colors as xterm */
  1747. for(i = 16, r = 0; r < 6; r++)
  1748. for(g = 0; g < 6; g++)
  1749. for(b = 0; b < 6; b++) {
  1750. xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1751. xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1752. xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1753. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
  1754. dc.col[i] = white;
  1755. fprintf(stderr, "Could not allocate color %d\n", i);
  1756. } else
  1757. dc.col[i] = dc.xft_col[i].pixel;
  1758. i++;
  1759. }
  1760. for(r = 0; r < 24; r++, i++) {
  1761. xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
  1762. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
  1763. dc.col[i] = white;
  1764. fprintf(stderr, "Could not allocate color %d\n", i);
  1765. } else
  1766. dc.col[i] = dc.xft_col[i].pixel;
  1767. }
  1768. }
  1769. void
  1770. xclear(int x1, int y1, int x2, int y2) {
  1771. XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
  1772. XFillRectangle(xw.dpy, xw.buf, dc.gc,
  1773. BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
  1774. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1775. }
  1776. void
  1777. xhints(void) {
  1778. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1779. XWMHints wm = {.flags = InputHint, .input = 1};
  1780. XSizeHints *sizeh = NULL;
  1781. sizeh = XAllocSizeHints();
  1782. if(xw.isfixed == False) {
  1783. sizeh->flags = PSize | PResizeInc | PBaseSize;
  1784. sizeh->height = xw.h;
  1785. sizeh->width = xw.w;
  1786. sizeh->height_inc = xw.ch;
  1787. sizeh->width_inc = xw.cw;
  1788. sizeh->base_height = 2*BORDER;
  1789. sizeh->base_width = 2*BORDER;
  1790. } else {
  1791. sizeh->flags = PMaxSize | PMinSize;
  1792. sizeh->min_width = sizeh->max_width = xw.fw;
  1793. sizeh->min_height = sizeh->max_height = xw.fh;
  1794. }
  1795. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  1796. XFree(sizeh);
  1797. }
  1798. void
  1799. xinitfont(Font *f, char *fontstr) {
  1800. f->xft_set = XftFontOpenName(xw.dpy, xw.scr, fontstr);
  1801. if(!f->xft_set)
  1802. die("st: can't open font %s.\n", fontstr);
  1803. f->ascent = f->xft_set->ascent;
  1804. f->descent = f->xft_set->descent;
  1805. f->lbearing = 0;
  1806. f->rbearing = f->xft_set->max_advance_width;
  1807. }
  1808. void
  1809. initfonts(char *fontstr, char *bfontstr, char *ifontstr, char *ibfontstr) {
  1810. xinitfont(&dc.font, fontstr);
  1811. xinitfont(&dc.bfont, bfontstr);
  1812. xinitfont(&dc.ifont, ifontstr);
  1813. xinitfont(&dc.ibfont, ibfontstr);
  1814. }
  1815. void
  1816. xinit(void) {
  1817. XSetWindowAttributes attrs;
  1818. Cursor cursor;
  1819. Window parent;
  1820. int sw, sh, major, minor;
  1821. if(!(xw.dpy = XOpenDisplay(NULL)))
  1822. die("Can't open display\n");
  1823. xw.scr = XDefaultScreen(xw.dpy);
  1824. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  1825. /* font */
  1826. initfonts(FONT, BOLDFONT, ITALICFONT, ITALICBOLDFONT);
  1827. /* XXX: Assuming same size for bold font */
  1828. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1829. xw.ch = dc.font.ascent + dc.font.descent;
  1830. /* colors */
  1831. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1832. xloadcols();
  1833. /* adjust fixed window geometry */
  1834. if(xw.isfixed) {
  1835. sw = DisplayWidth(xw.dpy, xw.scr);
  1836. sh = DisplayHeight(xw.dpy, xw.scr);
  1837. if(xw.fx < 0)
  1838. xw.fx = sw + xw.fx - xw.fw - 1;
  1839. if(xw.fy < 0)
  1840. xw.fy = sh + xw.fy - xw.fh - 1;
  1841. xw.h = xw.fh;
  1842. xw.w = xw.fw;
  1843. } else {
  1844. /* window - default size */
  1845. xw.h = 2*BORDER + term.row * xw.ch;
  1846. xw.w = 2*BORDER + term.col * xw.cw;
  1847. xw.fx = 0;
  1848. xw.fy = 0;
  1849. }
  1850. attrs.background_pixel = dc.col[DefaultBG];
  1851. attrs.border_pixel = dc.col[DefaultBG];
  1852. attrs.bit_gravity = NorthWestGravity;
  1853. attrs.event_mask = FocusChangeMask | KeyPressMask
  1854. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1855. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  1856. attrs.colormap = xw.cmap;
  1857. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  1858. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  1859. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1860. xw.vis,
  1861. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1862. | CWColormap,
  1863. &attrs);
  1864. /* double buffering */
  1865. if(!XdbeQueryExtension(xw.dpy, &major, &minor))
  1866. die("Xdbe extension is not present\n");
  1867. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  1868. /* Xft rendering context */
  1869. xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  1870. /* input methods */
  1871. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1872. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1873. | XIMStatusNothing, XNClientWindow, xw.win,
  1874. XNFocusWindow, xw.win, NULL);
  1875. /* gc */
  1876. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1877. /* white cursor, black outline */
  1878. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1879. XDefineCursor(xw.dpy, xw.win, cursor);
  1880. XRecolorCursor(xw.dpy, cursor,
  1881. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1882. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1883. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1884. xresettitle();
  1885. XMapWindow(xw.dpy, xw.win);
  1886. xhints();
  1887. XSync(xw.dpy, 0);
  1888. }
  1889. void
  1890. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1891. int fg = base.fg, bg = base.bg, temp;
  1892. int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1893. Font *font = &dc.font;
  1894. XGlyphInfo extents;
  1895. /* only switch default fg/bg if term is in RV mode */
  1896. if(IS_SET(MODE_REVERSE)) {
  1897. if(fg == DefaultFG)
  1898. fg = DefaultBG;
  1899. if(bg == DefaultBG)
  1900. bg = DefaultFG;
  1901. }
  1902. if(base.mode & ATTR_REVERSE)
  1903. temp = fg, fg = bg, bg = temp;
  1904. if(base.mode & ATTR_BOLD) {
  1905. fg += 8;
  1906. font = &dc.bfont;
  1907. }
  1908. if(base.mode & ATTR_ITALIC)
  1909. font = &dc.ifont;
  1910. if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
  1911. font = &dc.ibfont;
  1912. XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
  1913. XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
  1914. XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen, &extents);
  1915. width = extents.xOff;
  1916. XftDrawRect(xw.xft_draw, &dc.xft_col[bg], winx, winy - font->ascent, width, xw.ch);
  1917. XftDrawStringUtf8(xw.xft_draw, &dc.xft_col[fg], font->xft_set, winx, winy, (FcChar8 *)s, bytelen);
  1918. if(base.mode & ATTR_UNDERLINE)
  1919. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1920. }
  1921. void
  1922. xdrawcursor(void) {
  1923. static int oldx = 0;
  1924. static int oldy = 0;
  1925. int sl;
  1926. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1927. LIMIT(oldx, 0, term.col-1);
  1928. LIMIT(oldy, 0, term.row-1);
  1929. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1930. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1931. /* remove the old cursor */
  1932. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1933. sl = utf8size(term.line[oldy][oldx].c);
  1934. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1935. } else
  1936. xclear(oldx, oldy, oldx, oldy);
  1937. /* draw the new one */
  1938. if(!(term.c.state & CURSOR_HIDE)) {
  1939. if(!(xw.state & WIN_FOCUSED))
  1940. g.bg = DefaultUCS;
  1941. if(IS_SET(MODE_REVERSE))
  1942. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  1943. sl = utf8size(g.c);
  1944. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1945. oldx = term.c.x, oldy = term.c.y;
  1946. }
  1947. }
  1948. void
  1949. xresettitle(void) {
  1950. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1951. }
  1952. void
  1953. redraw(void) {
  1954. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  1955. xclear(0, 0, xw.w, xw.h);
  1956. tfulldirt();
  1957. draw();
  1958. XSync(xw.dpy, False); /* necessary for a good tput flash */
  1959. nanosleep(&tv, NULL);
  1960. }
  1961. void
  1962. draw() {
  1963. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  1964. drawregion(0, 0, term.col, term.row);
  1965. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  1966. }
  1967. void
  1968. drawregion(int x1, int y1, int x2, int y2) {
  1969. int ic, ib, x, y, ox, sl;
  1970. Glyph base, new;
  1971. char buf[DRAW_BUF_SIZ];
  1972. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
  1973. if((sel.alt && !alt) || (!sel.alt && alt))
  1974. ena_sel = 0;
  1975. if(!(xw.state & WIN_VISIBLE))
  1976. return;
  1977. for(y = y1; y < y2; y++) {
  1978. if(!term.dirty[y])
  1979. continue;
  1980. xclear(0, y, term.col, y);
  1981. term.dirty[y] = 0;
  1982. base = term.line[y][0];
  1983. ic = ib = ox = 0;
  1984. for(x = x1; x < x2; x++) {
  1985. new = term.line[y][x];
  1986. if(ena_sel && *(new.c) && selected(x, y))
  1987. new.mode ^= ATTR_REVERSE;
  1988. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1989. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1990. xdraws(buf, base, ox, y, ic, ib);
  1991. ic = ib = 0;
  1992. }
  1993. if(new.state & GLYPH_SET) {
  1994. if(ib == 0) {
  1995. ox = x;
  1996. base = new;
  1997. }
  1998. sl = utf8size(new.c);
  1999. memcpy(buf+ib, new.c, sl);
  2000. ib += sl;
  2001. ++ic;
  2002. }
  2003. }
  2004. if(ib > 0)
  2005. xdraws(buf, base, ox, y, ic, ib);
  2006. }
  2007. xdrawcursor();
  2008. }
  2009. void
  2010. expose(XEvent *ev) {
  2011. XExposeEvent *e = &ev->xexpose;
  2012. if(xw.state & WIN_REDRAW) {
  2013. if(!e->count)
  2014. xw.state &= ~WIN_REDRAW;
  2015. }
  2016. }
  2017. void
  2018. visibility(XEvent *ev) {
  2019. XVisibilityEvent *e = &ev->xvisibility;
  2020. if(e->state == VisibilityFullyObscured)
  2021. xw.state &= ~WIN_VISIBLE;
  2022. else if(!(xw.state & WIN_VISIBLE))
  2023. /* need a full redraw for next Expose, not just a buf copy */
  2024. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2025. }
  2026. void
  2027. unmap(XEvent *ev) {
  2028. xw.state &= ~WIN_VISIBLE;
  2029. }
  2030. void
  2031. xseturgency(int add) {
  2032. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2033. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2034. XSetWMHints(xw.dpy, xw.win, h);
  2035. XFree(h);
  2036. }
  2037. void
  2038. focus(XEvent *ev) {
  2039. if(ev->type == FocusIn) {
  2040. xw.state |= WIN_FOCUSED;
  2041. xseturgency(0);
  2042. } else
  2043. xw.state &= ~WIN_FOCUSED;
  2044. }
  2045. char*
  2046. kmap(KeySym k, uint state) {
  2047. int i;
  2048. state &= ~Mod2Mask;
  2049. for(i = 0; i < LEN(key); i++) {
  2050. uint mask = key[i].mask;
  2051. if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
  2052. return (char*)key[i].s;
  2053. }
  2054. return NULL;
  2055. }
  2056. void
  2057. kpress(XEvent *ev) {
  2058. XKeyEvent *e = &ev->xkey;
  2059. KeySym ksym;
  2060. char buf[32];
  2061. char *customkey;
  2062. int len;
  2063. int meta;
  2064. int shift;
  2065. Status status;
  2066. if (IS_SET(MODE_KBDLOCK))
  2067. return;
  2068. meta = e->state & Mod1Mask;
  2069. shift = e->state & ShiftMask;
  2070. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  2071. /* 1. custom keys from config.h */
  2072. if((customkey = kmap(ksym, e->state)))
  2073. ttywrite(customkey, strlen(customkey));
  2074. /* 2. hardcoded (overrides X lookup) */
  2075. else
  2076. switch(ksym) {
  2077. case XK_Up:
  2078. case XK_Down:
  2079. case XK_Left:
  2080. case XK_Right:
  2081. /* XXX: shift up/down doesn't work */
  2082. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
  2083. ttywrite(buf, 3);
  2084. break;
  2085. case XK_Insert:
  2086. if(shift)
  2087. selpaste();
  2088. break;
  2089. case XK_Return:
  2090. if(IS_SET(MODE_CRLF))
  2091. ttywrite("\r\n", 2);
  2092. else
  2093. ttywrite("\r", 1);
  2094. break;
  2095. /* 3. X lookup */
  2096. default:
  2097. if(len > 0) {
  2098. if(meta && len == 1)
  2099. ttywrite("\033", 1);
  2100. ttywrite(buf, len);
  2101. }
  2102. break;
  2103. }
  2104. }
  2105. void
  2106. cmessage(XEvent *e) {
  2107. /* See xembed specs
  2108. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2109. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2110. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2111. xw.state |= WIN_FOCUSED;
  2112. xseturgency(0);
  2113. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2114. xw.state &= ~WIN_FOCUSED;
  2115. }
  2116. }
  2117. }
  2118. void
  2119. resize(XEvent *e) {
  2120. int col, row;
  2121. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2122. return;
  2123. xw.w = e->xconfigure.width;
  2124. xw.h = e->xconfigure.height;
  2125. col = (xw.w - 2*BORDER) / xw.cw;
  2126. row = (xw.h - 2*BORDER) / xw.ch;
  2127. if(col == term.col && row == term.row)
  2128. return;
  2129. xclear(0, 0, xw.w, xw.h);
  2130. tresize(col, row);
  2131. xresize(col, row);
  2132. ttyresize();
  2133. }
  2134. void
  2135. run(void) {
  2136. XEvent ev;
  2137. fd_set rfd;
  2138. int xfd = XConnectionNumber(xw.dpy), i;
  2139. struct timeval drawtimeout, *tv = NULL;
  2140. for(i = 0;; i++) {
  2141. FD_ZERO(&rfd);
  2142. FD_SET(cmdfd, &rfd);
  2143. FD_SET(xfd, &rfd);
  2144. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  2145. if(errno == EINTR)
  2146. continue;
  2147. die("select failed: %s\n", SERRNO);
  2148. }
  2149. /*
  2150. * Stop after a certain number of reads so the user does not
  2151. * feel like the system is stuttering.
  2152. */
  2153. if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
  2154. ttyread();
  2155. /*
  2156. * Just wait a bit so it isn't disturbing the
  2157. * user and the system is able to write something.
  2158. */
  2159. drawtimeout.tv_sec = 0;
  2160. drawtimeout.tv_usec = 5;
  2161. tv = &drawtimeout;
  2162. continue;
  2163. }
  2164. i = 0;
  2165. tv = NULL;
  2166. while(XPending(xw.dpy)) {
  2167. XNextEvent(xw.dpy, &ev);
  2168. if(XFilterEvent(&ev, xw.win))
  2169. continue;
  2170. if(handler[ev.type])
  2171. (handler[ev.type])(&ev);
  2172. }
  2173. draw();
  2174. XFlush(xw.dpy);
  2175. }
  2176. }
  2177. int
  2178. main(int argc, char *argv[]) {
  2179. int i, bitm, xr, yr;
  2180. uint wr, hr;
  2181. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2182. xw.isfixed = False;
  2183. for(i = 1; i < argc; i++) {
  2184. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2185. case 't':
  2186. if(++i < argc) opt_title = argv[i];
  2187. break;
  2188. case 'c':
  2189. if(++i < argc) opt_class = argv[i];
  2190. break;
  2191. case 'w':
  2192. if(++i < argc) opt_embed = argv[i];
  2193. break;
  2194. case 'f':
  2195. if(++i < argc) opt_io = argv[i];
  2196. break;
  2197. case 'e':
  2198. /* eat every remaining arguments */
  2199. if(++i < argc) opt_cmd = &argv[i];
  2200. goto run;
  2201. case 'g':
  2202. if(++i >= argc)
  2203. break;
  2204. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2205. if(bitm & XValue)
  2206. xw.fx = xr;
  2207. if(bitm & YValue)
  2208. xw.fy = yr;
  2209. if(bitm & WidthValue)
  2210. xw.fw = (int)wr;
  2211. if(bitm & HeightValue)
  2212. xw.fh = (int)hr;
  2213. if(bitm & XNegative && xw.fx == 0)
  2214. xw.fx = -1;
  2215. if(bitm & XNegative && xw.fy == 0)
  2216. xw.fy = -1;
  2217. if(xw.fh != 0 && xw.fw != 0)
  2218. xw.isfixed = True;
  2219. break;
  2220. case 'v':
  2221. default:
  2222. die(USAGE);
  2223. }
  2224. }
  2225. run:
  2226. setlocale(LC_CTYPE, "");
  2227. tnew(80, 24);
  2228. ttynew();
  2229. xinit();
  2230. selinit();
  2231. run();
  2232. return 0;
  2233. }