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.

3548 lines
76 KiB

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