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.

3691 lines
80 KiB

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