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.

2959 lines
64 KiB

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