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.

2888 lines
63 KiB

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