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.

2855 lines
62 KiB

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