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.

3746 lines
81 KiB

13 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
11 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
11 years ago
14 years ago
13 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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
11 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 CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
  71. #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
  72. #define IS_TRUECOL(x) (1 << 24 & (x))
  73. #define TRUERED(x) (((x) & 0xff0000) >> 8)
  74. #define TRUEGREEN(x) (((x) & 0xff00))
  75. #define TRUEBLUE(x) (((x) & 0xff) << 8)
  76. #define VT102ID "\033[?6c"
  77. enum glyph_attribute {
  78. ATTR_NULL = 0,
  79. ATTR_REVERSE = 1,
  80. ATTR_UNDERLINE = 2,
  81. ATTR_BOLD = 4,
  82. ATTR_GFX = 8,
  83. ATTR_ITALIC = 16,
  84. ATTR_BLINK = 32,
  85. ATTR_WRAP = 64,
  86. };
  87. enum cursor_movement {
  88. CURSOR_SAVE,
  89. CURSOR_LOAD
  90. };
  91. enum cursor_state {
  92. CURSOR_DEFAULT = 0,
  93. CURSOR_WRAPNEXT = 1,
  94. CURSOR_ORIGIN = 2
  95. };
  96. enum term_mode {
  97. MODE_WRAP = 1,
  98. MODE_INSERT = 2,
  99. MODE_APPKEYPAD = 4,
  100. MODE_ALTSCREEN = 8,
  101. MODE_CRLF = 16,
  102. MODE_MOUSEBTN = 32,
  103. MODE_MOUSEMOTION = 64,
  104. MODE_REVERSE = 128,
  105. MODE_KBDLOCK = 256,
  106. MODE_HIDE = 512,
  107. MODE_ECHO = 1024,
  108. MODE_APPCURSOR = 2048,
  109. MODE_MOUSESGR = 4096,
  110. MODE_8BIT = 8192,
  111. MODE_BLINK = 16384,
  112. MODE_FBLINK = 32768,
  113. MODE_FOCUS = 65536,
  114. MODE_MOUSEX10 = 131072,
  115. MODE_MOUSEMANY = 262144,
  116. MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
  117. |MODE_MOUSEMANY,
  118. };
  119. enum escape_state {
  120. ESC_START = 1,
  121. ESC_CSI = 2,
  122. ESC_STR = 4, /* DSC, OSC, PM, APC */
  123. ESC_ALTCHARSET = 8,
  124. ESC_STR_END = 16, /* a final string was encountered */
  125. ESC_TEST = 32, /* Enter in test mode */
  126. };
  127. enum window_state {
  128. WIN_VISIBLE = 1,
  129. WIN_REDRAW = 2,
  130. WIN_FOCUSED = 4
  131. };
  132. enum selection_type {
  133. SEL_REGULAR = 1,
  134. SEL_RECTANGULAR = 2
  135. };
  136. enum selection_snap {
  137. SNAP_WORD = 1,
  138. SNAP_LINE = 2
  139. };
  140. typedef unsigned char uchar;
  141. typedef unsigned int uint;
  142. typedef unsigned long ulong;
  143. typedef unsigned short ushort;
  144. typedef struct {
  145. char c[UTF_SIZ]; /* character code */
  146. uchar mode; /* attribute flags */
  147. ulong fg; /* foreground */
  148. ulong bg; /* background */
  149. } Glyph;
  150. typedef Glyph *Line;
  151. typedef struct {
  152. Glyph attr; /* current char attributes */
  153. int x;
  154. int y;
  155. char state;
  156. } TCursor;
  157. /* CSI Escape sequence structs */
  158. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  159. typedef struct {
  160. char buf[ESC_BUF_SIZ]; /* raw string */
  161. int len; /* raw string length */
  162. char priv;
  163. int arg[ESC_ARG_SIZ];
  164. int narg; /* nb of args */
  165. char mode;
  166. } CSIEscape;
  167. /* STR Escape sequence structs */
  168. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  169. typedef struct {
  170. char type; /* ESC type ... */
  171. char buf[STR_BUF_SIZ]; /* raw string */
  172. int len; /* raw string length */
  173. char *args[STR_ARG_SIZ];
  174. int narg; /* nb of args */
  175. } STREscape;
  176. /* Internal representation of the screen */
  177. typedef struct {
  178. int row; /* nb row */
  179. int col; /* nb col */
  180. Line *line; /* screen */
  181. Line *alt; /* alternate screen */
  182. bool *dirty; /* dirtyness of lines */
  183. TCursor c; /* cursor */
  184. int top; /* top scroll limit */
  185. int bot; /* bottom scroll limit */
  186. int mode; /* terminal mode flags */
  187. int esc; /* escape state flags */
  188. bool numlock; /* lock numbers in keyboard */
  189. bool *tabs;
  190. } Term;
  191. /* Purely graphic info */
  192. typedef struct {
  193. Display *dpy;
  194. Colourmap cmap;
  195. Window win;
  196. Drawable buf;
  197. Atom xembed, wmdeletewin;
  198. XIM xim;
  199. XIC xic;
  200. Draw draw;
  201. Visual *vis;
  202. XSetWindowAttributes attrs;
  203. int scr;
  204. bool isfixed; /* is fixed geometry? */
  205. int fx, fy, fw, fh; /* fixed geometry */
  206. int tw, th; /* tty width and height */
  207. int w, h; /* window width and height */
  208. int ch; /* char height */
  209. int cw; /* char width */
  210. char state; /* focus, redraw, visible */
  211. } XWindow;
  212. typedef struct {
  213. int b;
  214. uint mask;
  215. char s[ESC_BUF_SIZ];
  216. } Mousekey;
  217. typedef struct {
  218. KeySym k;
  219. uint mask;
  220. char s[ESC_BUF_SIZ];
  221. /* three valued logic variables: 0 indifferent, 1 on, -1 off */
  222. signed char appkey; /* application keypad */
  223. signed char appcursor; /* application cursor */
  224. signed char crlf; /* crlf mode */
  225. } Key;
  226. typedef struct {
  227. int mode;
  228. int type;
  229. int snap;
  230. /*
  231. * Selection variables:
  232. * nb normalized coordinates of the beginning of the selection
  233. * ne normalized coordinates of the end of the selection
  234. * ob original coordinates of the beginning of the selection
  235. * oe original coordinates of the end of the selection
  236. */
  237. struct {
  238. int x, y;
  239. } nb, ne, ob, oe;
  240. char *clip;
  241. Atom xtarget;
  242. bool alt;
  243. struct timeval tclick1;
  244. struct timeval tclick2;
  245. } Selection;
  246. typedef union {
  247. int i;
  248. unsigned int ui;
  249. float f;
  250. const void *v;
  251. } Arg;
  252. typedef struct {
  253. unsigned int mod;
  254. KeySym keysym;
  255. void (*func)(const Arg *);
  256. const Arg arg;
  257. } Shortcut;
  258. /* function definitions used in config.h */
  259. static void clippaste(const Arg *);
  260. static void numlock(const Arg *);
  261. static void selpaste(const Arg *);
  262. static void xzoom(const Arg *);
  263. /* Config.h for applying patches and the configuration. */
  264. #include "config.h"
  265. /* Font structure */
  266. typedef struct {
  267. int height;
  268. int width;
  269. int ascent;
  270. int descent;
  271. short lbearing;
  272. short rbearing;
  273. XftFont *match;
  274. FcFontSet *set;
  275. FcPattern *pattern;
  276. } Font;
  277. /* Drawing Context */
  278. typedef struct {
  279. Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
  280. Font font, bfont, ifont, ibfont;
  281. GC gc;
  282. } DC;
  283. static void die(const char *, ...);
  284. static void draw(void);
  285. static void redraw(int);
  286. static void drawregion(int, int, int, int);
  287. static void execsh(void);
  288. static void sigchld(int);
  289. static void run(void);
  290. static void csidump(void);
  291. static void csihandle(void);
  292. static void csiparse(void);
  293. static void csireset(void);
  294. static void strdump(void);
  295. static void strhandle(void);
  296. static void strparse(void);
  297. static void strreset(void);
  298. static int tattrset(int);
  299. static void tclearregion(int, int, int, int);
  300. static void tcursor(int);
  301. static void tdeletechar(int);
  302. static void tdeleteline(int);
  303. static void tinsertblank(int);
  304. static void tinsertblankline(int);
  305. static void tmoveto(int, int);
  306. static void tmoveato(int x, int y);
  307. static void tnew(int, int);
  308. static void tnewline(int);
  309. static void tputtab(bool);
  310. static void tputc(char *, int);
  311. static void treset(void);
  312. static int tresize(int, int);
  313. static void tscrollup(int, int);
  314. static void tscrolldown(int, int);
  315. static void tsetattr(int*, int);
  316. static void tsetchar(char *, Glyph *, int, int);
  317. static void tsetscroll(int, int);
  318. static void tswapscreen(void);
  319. static void tsetdirt(int, int);
  320. static void tsetdirtattr(int);
  321. static void tsetmode(bool, bool, int *, int);
  322. static void tfulldirt(void);
  323. static void techo(char *, int);
  324. static ulong tdefcolor(int *, int *, int);
  325. static inline bool match(uint, uint);
  326. static void ttynew(void);
  327. static void ttyread(void);
  328. static void ttyresize(void);
  329. static void ttywrite(const char *, size_t);
  330. static void xdraws(char *, Glyph, int, int, int, int);
  331. static void xhints(void);
  332. static void xclear(int, int, int, int);
  333. static void xdrawcursor(void);
  334. static void xinit(void);
  335. static void xloadcols(void);
  336. static int xsetcolorname(int, const char *);
  337. static int xloadfont(Font *, FcPattern *);
  338. static void xloadfonts(char *, int);
  339. static int xloadfontset(Font *);
  340. static void xsettitle(char *);
  341. static void xresettitle(void);
  342. static void xsetpointermotion(int);
  343. static void xseturgency(int);
  344. static void xsetsel(char*);
  345. static void xtermclear(int, int, int, int);
  346. static void xunloadfont(Font *f);
  347. static void xunloadfonts(void);
  348. static void xresize(int, int);
  349. static void expose(XEvent *);
  350. static void visibility(XEvent *);
  351. static void unmap(XEvent *);
  352. static char *kmap(KeySym, uint);
  353. static void kpress(XEvent *);
  354. static void cmessage(XEvent *);
  355. static void cresize(int, int);
  356. static void resize(XEvent *);
  357. static void focus(XEvent *);
  358. static void brelease(XEvent *);
  359. static void bpress(XEvent *);
  360. static void bmotion(XEvent *);
  361. static void selnotify(XEvent *);
  362. static void selclear(XEvent *);
  363. static void selrequest(XEvent *);
  364. static void selinit(void);
  365. static void selsort(void);
  366. static inline bool selected(int, int);
  367. static void selcopy(void);
  368. static void selscroll(int, int);
  369. static void selsnap(int, int *, int *, int);
  370. static int utf8decode(char *, long *);
  371. static int utf8encode(long *, char *);
  372. static int utf8size(char *);
  373. static int isfullutf8(char *, int);
  374. static ssize_t xwrite(int, char *, size_t);
  375. static void *xmalloc(size_t);
  376. static void *xrealloc(void *, size_t);
  377. static void *xcalloc(size_t, size_t);
  378. static void (*handler[LASTEvent])(XEvent *) = {
  379. [KeyPress] = kpress,
  380. [ClientMessage] = cmessage,
  381. [ConfigureNotify] = resize,
  382. [VisibilityNotify] = visibility,
  383. [UnmapNotify] = unmap,
  384. [Expose] = expose,
  385. [FocusIn] = focus,
  386. [FocusOut] = focus,
  387. [MotionNotify] = bmotion,
  388. [ButtonPress] = bpress,
  389. [ButtonRelease] = brelease,
  390. [SelectionClear] = selclear,
  391. [SelectionNotify] = selnotify,
  392. [SelectionRequest] = selrequest,
  393. };
  394. /* Globals */
  395. static DC dc;
  396. static XWindow xw;
  397. static Term term;
  398. static CSIEscape csiescseq;
  399. static STREscape strescseq;
  400. static int cmdfd;
  401. static pid_t pid;
  402. static Selection sel;
  403. static int iofd = -1;
  404. static char **opt_cmd = NULL;
  405. static char *opt_io = NULL;
  406. static char *opt_title = NULL;
  407. static char *opt_embed = NULL;
  408. static char *opt_class = NULL;
  409. static char *opt_font = NULL;
  410. static int oldbutton = 3; /* button event on startup: 3 = release */
  411. static char *usedfont = NULL;
  412. static int usedfontsize = 0;
  413. /* Font Ring Cache */
  414. enum {
  415. FRC_NORMAL,
  416. FRC_ITALIC,
  417. FRC_BOLD,
  418. FRC_ITALICBOLD
  419. };
  420. typedef struct {
  421. XftFont *font;
  422. int flags;
  423. } Fontcache;
  424. /* Fontcache is an array now. A new font will be appended to the array. */
  425. static Fontcache frc[16];
  426. static int 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 & 0x80) { /* 0xxxxxxx */
  466. *u = c;
  467. return rtn;
  468. } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
  469. *u = c & 0x1F;
  470. n = 1;
  471. } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
  472. *u = c & 0x0F;
  473. n = 2;
  474. } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
  475. *u = c & 0x07;
  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 & 0xC0) != 0x80) /* 10xxxxxx */
  483. goto invalid;
  484. *u <<= 6;
  485. *u |= c & 0x3F;
  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) | 0xC0; /* 110xxxxx */
  510. n = 1;
  511. } else if(uc < 0x10000) {
  512. *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
  513. n = 2;
  514. } else if(uc <= 0x10FFFF) {
  515. *sp = (uc >> 18) | 0xF0; /* 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)) & 0x3F) | 0x80; /* 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 & 0xE0) == 0xC0 && b == 1) {
  541. return 0;
  542. } else if((*c1 & 0xF0) == 0xE0 &&
  543. ((b == 1) ||
  544. ((b == 2) && (*c2 & 0xC0) == 0x80))) {
  545. return 0;
  546. } else if((*c1 & 0xF8) == 0xF0 &&
  547. ((b == 1) ||
  548. ((b == 2) && (*c2 & 0xC0) == 0x80) ||
  549. ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
  550. return 0;
  551. } else {
  552. return 1;
  553. }
  554. }
  555. int
  556. utf8size(char *s) {
  557. uchar c = *s;
  558. if(~c & 0x80) {
  559. return 1;
  560. } else if((c & 0xE0) == 0xC0) {
  561. return 2;
  562. } else if((c & 0xF0) == 0xE0) {
  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. ulong
  1408. tdefcolor(int *attr, int *npar, int l) {
  1409. long idx = -1;
  1410. uint r, g, b;
  1411. switch (attr[*npar + 1]) {
  1412. case 2: /* direct colour in RGB space */
  1413. if (*npar + 4 >= l) {
  1414. fprintf(stderr,
  1415. "erresc(38): Incorrect number of parameters (%d)\n",
  1416. *npar);
  1417. break;
  1418. }
  1419. r = attr[*npar + 2];
  1420. g = attr[*npar + 3];
  1421. b = attr[*npar + 4];
  1422. *npar += 4;
  1423. if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
  1424. fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
  1425. r, g, b);
  1426. else
  1427. idx = TRUECOLOR(r, g, b);
  1428. break;
  1429. case 5: /* indexed colour */
  1430. if (*npar + 2 >= l) {
  1431. fprintf(stderr,
  1432. "erresc(38): Incorrect number of parameters (%d)\n",
  1433. *npar);
  1434. break;
  1435. }
  1436. *npar += 2;
  1437. if(!BETWEEN(attr[*npar], 0, 255))
  1438. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
  1439. else
  1440. idx = attr[*npar];
  1441. break;
  1442. case 0: /* implemented defined (only foreground) */
  1443. case 1: /* transparent */
  1444. case 3: /* direct colour in CMY space */
  1445. case 4: /* direct colour in CMYK space */
  1446. default:
  1447. fprintf(stderr,
  1448. "erresc(38): gfx attr %d unknown\n", attr[*npar]);
  1449. }
  1450. return idx;
  1451. }
  1452. void
  1453. tsetattr(int *attr, int l) {
  1454. int i;
  1455. ulong idx;
  1456. for(i = 0; i < l; i++) {
  1457. switch(attr[i]) {
  1458. case 0:
  1459. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
  1460. | ATTR_BOLD | ATTR_ITALIC \
  1461. | ATTR_BLINK);
  1462. term.c.attr.fg = defaultfg;
  1463. term.c.attr.bg = defaultbg;
  1464. break;
  1465. case 1:
  1466. term.c.attr.mode |= ATTR_BOLD;
  1467. break;
  1468. case 3:
  1469. term.c.attr.mode |= ATTR_ITALIC;
  1470. break;
  1471. case 4:
  1472. term.c.attr.mode |= ATTR_UNDERLINE;
  1473. break;
  1474. case 5: /* slow blink */
  1475. case 6: /* rapid blink */
  1476. term.c.attr.mode |= ATTR_BLINK;
  1477. break;
  1478. case 7:
  1479. term.c.attr.mode |= ATTR_REVERSE;
  1480. break;
  1481. case 21:
  1482. case 22:
  1483. term.c.attr.mode &= ~ATTR_BOLD;
  1484. break;
  1485. case 23:
  1486. term.c.attr.mode &= ~ATTR_ITALIC;
  1487. break;
  1488. case 24:
  1489. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1490. break;
  1491. case 25:
  1492. case 26:
  1493. term.c.attr.mode &= ~ATTR_BLINK;
  1494. break;
  1495. case 27:
  1496. term.c.attr.mode &= ~ATTR_REVERSE;
  1497. break;
  1498. case 38:
  1499. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1500. term.c.attr.fg = idx;
  1501. break;
  1502. case 39:
  1503. term.c.attr.fg = defaultfg;
  1504. break;
  1505. case 48:
  1506. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1507. term.c.attr.bg = idx;
  1508. break;
  1509. case 49:
  1510. term.c.attr.bg = defaultbg;
  1511. break;
  1512. default:
  1513. if(BETWEEN(attr[i], 30, 37)) {
  1514. term.c.attr.fg = attr[i] - 30;
  1515. } else if(BETWEEN(attr[i], 40, 47)) {
  1516. term.c.attr.bg = attr[i] - 40;
  1517. } else if(BETWEEN(attr[i], 90, 97)) {
  1518. term.c.attr.fg = attr[i] - 90 + 8;
  1519. } else if(BETWEEN(attr[i], 100, 107)) {
  1520. term.c.attr.bg = attr[i] - 100 + 8;
  1521. } else {
  1522. fprintf(stderr,
  1523. "erresc(default): gfx attr %d unknown\n",
  1524. attr[i]), csidump();
  1525. }
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. void
  1531. tsetscroll(int t, int b) {
  1532. int temp;
  1533. LIMIT(t, 0, term.row-1);
  1534. LIMIT(b, 0, term.row-1);
  1535. if(t > b) {
  1536. temp = t;
  1537. t = b;
  1538. b = temp;
  1539. }
  1540. term.top = t;
  1541. term.bot = b;
  1542. }
  1543. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1544. void
  1545. tsetmode(bool priv, bool set, int *args, int narg) {
  1546. int *lim, mode;
  1547. bool alt;
  1548. for(lim = args + narg; args < lim; ++args) {
  1549. if(priv) {
  1550. switch(*args) {
  1551. break;
  1552. case 1: /* DECCKM -- Cursor key */
  1553. MODBIT(term.mode, set, MODE_APPCURSOR);
  1554. break;
  1555. case 5: /* DECSCNM -- Reverse video */
  1556. mode = term.mode;
  1557. MODBIT(term.mode, set, MODE_REVERSE);
  1558. if(mode != term.mode)
  1559. redraw(REDRAW_TIMEOUT);
  1560. break;
  1561. case 6: /* DECOM -- Origin */
  1562. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1563. tmoveato(0, 0);
  1564. break;
  1565. case 7: /* DECAWM -- Auto wrap */
  1566. MODBIT(term.mode, set, MODE_WRAP);
  1567. break;
  1568. case 0: /* Error (IGNORED) */
  1569. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1570. case 3: /* DECCOLM -- Column (IGNORED) */
  1571. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1572. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1573. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1574. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1575. case 42: /* DECNRCM -- National characters (IGNORED) */
  1576. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1577. break;
  1578. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1579. MODBIT(term.mode, !set, MODE_HIDE);
  1580. break;
  1581. case 9: /* X10 mouse compatibility mode */
  1582. xsetpointermotion(0);
  1583. MODBIT(term.mode, 0, MODE_MOUSE);
  1584. MODBIT(term.mode, set, MODE_MOUSEX10);
  1585. break;
  1586. case 1000: /* 1000: report button press */
  1587. xsetpointermotion(0);
  1588. MODBIT(term.mode, 0, MODE_MOUSE);
  1589. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1590. break;
  1591. case 1002: /* 1002: report motion on button press */
  1592. xsetpointermotion(0);
  1593. MODBIT(term.mode, 0, MODE_MOUSE);
  1594. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1595. break;
  1596. case 1003: /* 1003: enable all mouse motions */
  1597. xsetpointermotion(set);
  1598. MODBIT(term.mode, 0, MODE_MOUSE);
  1599. MODBIT(term.mode, set, MODE_MOUSEMANY);
  1600. break;
  1601. case 1004: /* 1004: send focus events to tty */
  1602. MODBIT(term.mode, set, MODE_FOCUS);
  1603. break;
  1604. case 1006: /* 1006: extended reporting mode */
  1605. MODBIT(term.mode, set, MODE_MOUSESGR);
  1606. break;
  1607. case 1034:
  1608. MODBIT(term.mode, set, MODE_8BIT);
  1609. break;
  1610. case 1049: /* = 1047 and 1048 */
  1611. case 47:
  1612. case 1047:
  1613. if (!allowaltscreen)
  1614. break;
  1615. alt = IS_SET(MODE_ALTSCREEN);
  1616. if(alt) {
  1617. tclearregion(0, 0, term.col-1,
  1618. term.row-1);
  1619. }
  1620. if(set ^ alt) /* set is always 1 or 0 */
  1621. tswapscreen();
  1622. if(*args != 1049)
  1623. break;
  1624. /* FALLTRU */
  1625. case 1048:
  1626. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1627. break;
  1628. /* Not implemented mouse modes. See comments there. */
  1629. case 1001: /* mouse highlight mode; can hang the
  1630. terminal by design when implemented. */
  1631. case 1005: /* UTF-8 mouse mode; will confuse
  1632. applications not supporting UTF-8
  1633. and luit. */
  1634. case 1015: /* urxvt mangled mouse mode; incompatible
  1635. and can be mistaken for other control
  1636. codes. */
  1637. default:
  1638. fprintf(stderr,
  1639. "erresc: unknown private set/reset mode %d\n",
  1640. *args);
  1641. break;
  1642. }
  1643. } else {
  1644. switch(*args) {
  1645. case 0: /* Error (IGNORED) */
  1646. break;
  1647. case 2: /* KAM -- keyboard action */
  1648. MODBIT(term.mode, set, MODE_KBDLOCK);
  1649. break;
  1650. case 4: /* IRM -- Insertion-replacement */
  1651. MODBIT(term.mode, set, MODE_INSERT);
  1652. break;
  1653. case 12: /* SRM -- Send/Receive */
  1654. MODBIT(term.mode, !set, MODE_ECHO);
  1655. break;
  1656. case 20: /* LNM -- Linefeed/new line */
  1657. MODBIT(term.mode, set, MODE_CRLF);
  1658. break;
  1659. default:
  1660. fprintf(stderr,
  1661. "erresc: unknown set/reset mode %d\n",
  1662. *args);
  1663. break;
  1664. }
  1665. }
  1666. }
  1667. }
  1668. void
  1669. csihandle(void) {
  1670. switch(csiescseq.mode) {
  1671. default:
  1672. unknown:
  1673. fprintf(stderr, "erresc: unknown csi ");
  1674. csidump();
  1675. /* die(""); */
  1676. break;
  1677. case '@': /* ICH -- Insert <n> blank char */
  1678. DEFAULT(csiescseq.arg[0], 1);
  1679. tinsertblank(csiescseq.arg[0]);
  1680. break;
  1681. case 'A': /* CUU -- Cursor <n> Up */
  1682. DEFAULT(csiescseq.arg[0], 1);
  1683. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1684. break;
  1685. case 'B': /* CUD -- Cursor <n> Down */
  1686. case 'e': /* VPR --Cursor <n> Down */
  1687. DEFAULT(csiescseq.arg[0], 1);
  1688. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1689. break;
  1690. case 'c': /* DA -- Device Attributes */
  1691. if(csiescseq.arg[0] == 0)
  1692. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1693. break;
  1694. case 'C': /* CUF -- Cursor <n> Forward */
  1695. case 'a': /* HPR -- Cursor <n> Forward */
  1696. DEFAULT(csiescseq.arg[0], 1);
  1697. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1698. break;
  1699. case 'D': /* CUB -- Cursor <n> Backward */
  1700. DEFAULT(csiescseq.arg[0], 1);
  1701. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1702. break;
  1703. case 'E': /* CNL -- Cursor <n> Down and first col */
  1704. DEFAULT(csiescseq.arg[0], 1);
  1705. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1706. break;
  1707. case 'F': /* CPL -- Cursor <n> Up and first col */
  1708. DEFAULT(csiescseq.arg[0], 1);
  1709. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1710. break;
  1711. case 'g': /* TBC -- Tabulation clear */
  1712. switch(csiescseq.arg[0]) {
  1713. case 0: /* clear current tab stop */
  1714. term.tabs[term.c.x] = 0;
  1715. break;
  1716. case 3: /* clear all the tabs */
  1717. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1718. break;
  1719. default:
  1720. goto unknown;
  1721. }
  1722. break;
  1723. case 'G': /* CHA -- Move to <col> */
  1724. case '`': /* HPA */
  1725. DEFAULT(csiescseq.arg[0], 1);
  1726. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1727. break;
  1728. case 'H': /* CUP -- Move to <row> <col> */
  1729. case 'f': /* HVP */
  1730. DEFAULT(csiescseq.arg[0], 1);
  1731. DEFAULT(csiescseq.arg[1], 1);
  1732. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1733. break;
  1734. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1735. DEFAULT(csiescseq.arg[0], 1);
  1736. while(csiescseq.arg[0]--)
  1737. tputtab(1);
  1738. break;
  1739. case 'J': /* ED -- Clear screen */
  1740. selclear(NULL);
  1741. switch(csiescseq.arg[0]) {
  1742. case 0: /* below */
  1743. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1744. if(term.c.y < term.row-1) {
  1745. tclearregion(0, term.c.y+1, term.col-1,
  1746. term.row-1);
  1747. }
  1748. break;
  1749. case 1: /* above */
  1750. if(term.c.y > 1)
  1751. tclearregion(0, 0, term.col-1, term.c.y-1);
  1752. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1753. break;
  1754. case 2: /* all */
  1755. tclearregion(0, 0, term.col-1, term.row-1);
  1756. break;
  1757. default:
  1758. goto unknown;
  1759. }
  1760. break;
  1761. case 'K': /* EL -- Clear line */
  1762. switch(csiescseq.arg[0]) {
  1763. case 0: /* right */
  1764. tclearregion(term.c.x, term.c.y, term.col-1,
  1765. term.c.y);
  1766. break;
  1767. case 1: /* left */
  1768. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1769. break;
  1770. case 2: /* all */
  1771. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1772. break;
  1773. }
  1774. break;
  1775. case 'S': /* SU -- Scroll <n> line up */
  1776. DEFAULT(csiescseq.arg[0], 1);
  1777. tscrollup(term.top, csiescseq.arg[0]);
  1778. break;
  1779. case 'T': /* SD -- Scroll <n> line down */
  1780. DEFAULT(csiescseq.arg[0], 1);
  1781. tscrolldown(term.top, csiescseq.arg[0]);
  1782. break;
  1783. case 'L': /* IL -- Insert <n> blank lines */
  1784. DEFAULT(csiescseq.arg[0], 1);
  1785. tinsertblankline(csiescseq.arg[0]);
  1786. break;
  1787. case 'l': /* RM -- Reset Mode */
  1788. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1789. break;
  1790. case 'M': /* DL -- Delete <n> lines */
  1791. DEFAULT(csiescseq.arg[0], 1);
  1792. tdeleteline(csiescseq.arg[0]);
  1793. break;
  1794. case 'X': /* ECH -- Erase <n> char */
  1795. DEFAULT(csiescseq.arg[0], 1);
  1796. tclearregion(term.c.x, term.c.y,
  1797. term.c.x + csiescseq.arg[0] - 1, term.c.y);
  1798. break;
  1799. case 'P': /* DCH -- Delete <n> char */
  1800. DEFAULT(csiescseq.arg[0], 1);
  1801. tdeletechar(csiescseq.arg[0]);
  1802. break;
  1803. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1804. DEFAULT(csiescseq.arg[0], 1);
  1805. while(csiescseq.arg[0]--)
  1806. tputtab(0);
  1807. break;
  1808. case 'd': /* VPA -- Move to <row> */
  1809. DEFAULT(csiescseq.arg[0], 1);
  1810. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1811. break;
  1812. case 'h': /* SM -- Set terminal mode */
  1813. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1814. break;
  1815. case 'm': /* SGR -- Terminal attribute (color) */
  1816. tsetattr(csiescseq.arg, csiescseq.narg);
  1817. break;
  1818. case 'r': /* DECSTBM -- Set Scrolling Region */
  1819. if(csiescseq.priv) {
  1820. goto unknown;
  1821. } else {
  1822. DEFAULT(csiescseq.arg[0], 1);
  1823. DEFAULT(csiescseq.arg[1], term.row);
  1824. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1825. tmoveato(0, 0);
  1826. }
  1827. break;
  1828. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1829. tcursor(CURSOR_SAVE);
  1830. break;
  1831. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1832. tcursor(CURSOR_LOAD);
  1833. break;
  1834. }
  1835. }
  1836. void
  1837. csidump(void) {
  1838. int i;
  1839. uint c;
  1840. printf("ESC[");
  1841. for(i = 0; i < csiescseq.len; i++) {
  1842. c = csiescseq.buf[i] & 0xff;
  1843. if(isprint(c)) {
  1844. putchar(c);
  1845. } else if(c == '\n') {
  1846. printf("(\\n)");
  1847. } else if(c == '\r') {
  1848. printf("(\\r)");
  1849. } else if(c == 0x1b) {
  1850. printf("(\\e)");
  1851. } else {
  1852. printf("(%02x)", c);
  1853. }
  1854. }
  1855. putchar('\n');
  1856. }
  1857. void
  1858. csireset(void) {
  1859. memset(&csiescseq, 0, sizeof(csiescseq));
  1860. }
  1861. void
  1862. strhandle(void) {
  1863. char *p = NULL;
  1864. int i, j, narg;
  1865. strparse();
  1866. narg = strescseq.narg;
  1867. switch(strescseq.type) {
  1868. case ']': /* OSC -- Operating System Command */
  1869. switch(i = atoi(strescseq.args[0])) {
  1870. case 0:
  1871. case 1:
  1872. case 2:
  1873. if(narg > 1)
  1874. xsettitle(strescseq.args[1]);
  1875. break;
  1876. case 4: /* color set */
  1877. if(narg < 3)
  1878. break;
  1879. p = strescseq.args[2];
  1880. /* fall through */
  1881. case 104: /* color reset, here p = NULL */
  1882. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  1883. if (!xsetcolorname(j, p)) {
  1884. fprintf(stderr, "erresc: invalid color %s\n", p);
  1885. } else {
  1886. /*
  1887. * TODO if defaultbg color is changed, borders
  1888. * are dirty
  1889. */
  1890. redraw(0);
  1891. }
  1892. break;
  1893. default:
  1894. fprintf(stderr, "erresc: unknown str ");
  1895. strdump();
  1896. break;
  1897. }
  1898. break;
  1899. case 'k': /* old title set compatibility */
  1900. xsettitle(strescseq.args[0]);
  1901. break;
  1902. case 'P': /* DSC -- Device Control String */
  1903. case '_': /* APC -- Application Program Command */
  1904. case '^': /* PM -- Privacy Message */
  1905. default:
  1906. fprintf(stderr, "erresc: unknown str ");
  1907. strdump();
  1908. /* die(""); */
  1909. break;
  1910. }
  1911. }
  1912. void
  1913. strparse(void) {
  1914. char *p = strescseq.buf;
  1915. strescseq.narg = 0;
  1916. strescseq.buf[strescseq.len] = '\0';
  1917. while(p && strescseq.narg < STR_ARG_SIZ)
  1918. strescseq.args[strescseq.narg++] = strsep(&p, ";");
  1919. }
  1920. void
  1921. strdump(void) {
  1922. int i;
  1923. uint c;
  1924. printf("ESC%c", strescseq.type);
  1925. for(i = 0; i < strescseq.len; i++) {
  1926. c = strescseq.buf[i] & 0xff;
  1927. if(c == '\0') {
  1928. return;
  1929. } else if(isprint(c)) {
  1930. putchar(c);
  1931. } else if(c == '\n') {
  1932. printf("(\\n)");
  1933. } else if(c == '\r') {
  1934. printf("(\\r)");
  1935. } else if(c == 0x1b) {
  1936. printf("(\\e)");
  1937. } else {
  1938. printf("(%02x)", c);
  1939. }
  1940. }
  1941. printf("ESC\\\n");
  1942. }
  1943. void
  1944. strreset(void) {
  1945. memset(&strescseq, 0, sizeof(strescseq));
  1946. }
  1947. void
  1948. tputtab(bool forward) {
  1949. uint x = term.c.x;
  1950. if(forward) {
  1951. if(x == term.col)
  1952. return;
  1953. for(++x; x < term.col && !term.tabs[x]; ++x)
  1954. /* nothing */ ;
  1955. } else {
  1956. if(x == 0)
  1957. return;
  1958. for(--x; x > 0 && !term.tabs[x]; --x)
  1959. /* nothing */ ;
  1960. }
  1961. tmoveto(x, term.c.y);
  1962. }
  1963. void
  1964. techo(char *buf, int len) {
  1965. for(; len > 0; buf++, len--) {
  1966. char c = *buf;
  1967. if(c == '\033') { /* escape */
  1968. tputc("^", 1);
  1969. tputc("[", 1);
  1970. } else if(c < '\x20') { /* control code */
  1971. if(c != '\n' && c != '\r' && c != '\t') {
  1972. c |= '\x40';
  1973. tputc("^", 1);
  1974. }
  1975. tputc(&c, 1);
  1976. } else {
  1977. break;
  1978. }
  1979. }
  1980. if(len)
  1981. tputc(buf, len);
  1982. }
  1983. void
  1984. tputc(char *c, int len) {
  1985. uchar ascii = *c;
  1986. bool control = ascii < '\x20' || ascii == 0177;
  1987. if(iofd != -1) {
  1988. if(xwrite(iofd, c, len) < 0) {
  1989. fprintf(stderr, "Error writing in %s:%s\n",
  1990. opt_io, strerror(errno));
  1991. close(iofd);
  1992. iofd = -1;
  1993. }
  1994. }
  1995. /*
  1996. * STR sequences must be checked before anything else
  1997. * because it can use some control codes as part of the sequence.
  1998. */
  1999. if(term.esc & ESC_STR) {
  2000. switch(ascii) {
  2001. case '\033':
  2002. term.esc = ESC_START | ESC_STR_END;
  2003. break;
  2004. case '\a': /* backwards compatibility to xterm */
  2005. term.esc = 0;
  2006. strhandle();
  2007. break;
  2008. default:
  2009. if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
  2010. memmove(&strescseq.buf[strescseq.len], c, len);
  2011. strescseq.len += len;
  2012. } else {
  2013. /*
  2014. * Here is a bug in terminals. If the user never sends
  2015. * some code to stop the str or esc command, then st
  2016. * will stop responding. But this is better than
  2017. * silently failing with unknown characters. At least
  2018. * then users will report back.
  2019. *
  2020. * In the case users ever get fixed, here is the code:
  2021. */
  2022. /*
  2023. * term.esc = 0;
  2024. * strhandle();
  2025. */
  2026. }
  2027. }
  2028. return;
  2029. }
  2030. /*
  2031. * Actions of control codes must be performed as soon they arrive
  2032. * because they can be embedded inside a control sequence, and
  2033. * they must not cause conflicts with sequences.
  2034. */
  2035. if(control) {
  2036. switch(ascii) {
  2037. case '\t': /* HT */
  2038. tputtab(1);
  2039. return;
  2040. case '\b': /* BS */
  2041. tmoveto(term.c.x-1, term.c.y);
  2042. return;
  2043. case '\r': /* CR */
  2044. tmoveto(0, term.c.y);
  2045. return;
  2046. case '\f': /* LF */
  2047. case '\v': /* VT */
  2048. case '\n': /* LF */
  2049. /* go to first col if the mode is set */
  2050. tnewline(IS_SET(MODE_CRLF));
  2051. return;
  2052. case '\a': /* BEL */
  2053. if(!(xw.state & WIN_FOCUSED))
  2054. xseturgency(1);
  2055. return;
  2056. case '\033': /* ESC */
  2057. csireset();
  2058. term.esc = ESC_START;
  2059. return;
  2060. case '\016': /* SO */
  2061. case '\017': /* SI */
  2062. /*
  2063. * Different charsets are hard to handle. Applications
  2064. * should use the right alt charset escapes for the
  2065. * only reason they still exist: line drawing. The
  2066. * rest is incompatible history st should not support.
  2067. */
  2068. return;
  2069. case '\032': /* SUB */
  2070. case '\030': /* CAN */
  2071. csireset();
  2072. return;
  2073. case '\005': /* ENQ (IGNORED) */
  2074. case '\000': /* NUL (IGNORED) */
  2075. case '\021': /* XON (IGNORED) */
  2076. case '\023': /* XOFF (IGNORED) */
  2077. case 0177: /* DEL (IGNORED) */
  2078. return;
  2079. }
  2080. } else if(term.esc & ESC_START) {
  2081. if(term.esc & ESC_CSI) {
  2082. csiescseq.buf[csiescseq.len++] = ascii;
  2083. if(BETWEEN(ascii, 0x40, 0x7E)
  2084. || csiescseq.len >= \
  2085. sizeof(csiescseq.buf)-1) {
  2086. term.esc = 0;
  2087. csiparse();
  2088. csihandle();
  2089. }
  2090. } else if(term.esc & ESC_STR_END) {
  2091. term.esc = 0;
  2092. if(ascii == '\\')
  2093. strhandle();
  2094. } else if(term.esc & ESC_ALTCHARSET) {
  2095. switch(ascii) {
  2096. case '0': /* Line drawing set */
  2097. term.c.attr.mode |= ATTR_GFX;
  2098. break;
  2099. case 'B': /* USASCII */
  2100. term.c.attr.mode &= ~ATTR_GFX;
  2101. break;
  2102. case 'A': /* UK (IGNORED) */
  2103. case '<': /* multinational charset (IGNORED) */
  2104. case '5': /* Finnish (IGNORED) */
  2105. case 'C': /* Finnish (IGNORED) */
  2106. case 'K': /* German (IGNORED) */
  2107. break;
  2108. default:
  2109. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  2110. }
  2111. term.esc = 0;
  2112. } else if(term.esc & ESC_TEST) {
  2113. if(ascii == '8') { /* DEC screen alignment test. */
  2114. char E[UTF_SIZ] = "E";
  2115. int x, y;
  2116. for(x = 0; x < term.col; ++x) {
  2117. for(y = 0; y < term.row; ++y)
  2118. tsetchar(E, &term.c.attr, x, y);
  2119. }
  2120. }
  2121. term.esc = 0;
  2122. } else {
  2123. switch(ascii) {
  2124. case '[':
  2125. term.esc |= ESC_CSI;
  2126. break;
  2127. case '#':
  2128. term.esc |= ESC_TEST;
  2129. break;
  2130. case 'P': /* DCS -- Device Control String */
  2131. case '_': /* APC -- Application Program Command */
  2132. case '^': /* PM -- Privacy Message */
  2133. case ']': /* OSC -- Operating System Command */
  2134. case 'k': /* old title set compatibility */
  2135. strreset();
  2136. strescseq.type = ascii;
  2137. term.esc |= ESC_STR;
  2138. break;
  2139. case '(': /* set primary charset G0 */
  2140. term.esc |= ESC_ALTCHARSET;
  2141. break;
  2142. case ')': /* set secondary charset G1 (IGNORED) */
  2143. case '*': /* set tertiary charset G2 (IGNORED) */
  2144. case '+': /* set quaternary charset G3 (IGNORED) */
  2145. term.esc = 0;
  2146. break;
  2147. case 'D': /* IND -- Linefeed */
  2148. if(term.c.y == term.bot) {
  2149. tscrollup(term.top, 1);
  2150. } else {
  2151. tmoveto(term.c.x, term.c.y+1);
  2152. }
  2153. term.esc = 0;
  2154. break;
  2155. case 'E': /* NEL -- Next line */
  2156. tnewline(1); /* always go to first col */
  2157. term.esc = 0;
  2158. break;
  2159. case 'H': /* HTS -- Horizontal tab stop */
  2160. term.tabs[term.c.x] = 1;
  2161. term.esc = 0;
  2162. break;
  2163. case 'M': /* RI -- Reverse index */
  2164. if(term.c.y == term.top) {
  2165. tscrolldown(term.top, 1);
  2166. } else {
  2167. tmoveto(term.c.x, term.c.y-1);
  2168. }
  2169. term.esc = 0;
  2170. break;
  2171. case 'Z': /* DECID -- Identify Terminal */
  2172. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  2173. term.esc = 0;
  2174. break;
  2175. case 'c': /* RIS -- Reset to inital state */
  2176. treset();
  2177. term.esc = 0;
  2178. xresettitle();
  2179. xloadcols();
  2180. break;
  2181. case '=': /* DECPAM -- Application keypad */
  2182. term.mode |= MODE_APPKEYPAD;
  2183. term.esc = 0;
  2184. break;
  2185. case '>': /* DECPNM -- Normal keypad */
  2186. term.mode &= ~MODE_APPKEYPAD;
  2187. term.esc = 0;
  2188. break;
  2189. case '7': /* DECSC -- Save Cursor */
  2190. tcursor(CURSOR_SAVE);
  2191. term.esc = 0;
  2192. break;
  2193. case '8': /* DECRC -- Restore Cursor */
  2194. tcursor(CURSOR_LOAD);
  2195. term.esc = 0;
  2196. break;
  2197. case '\\': /* ST -- Stop */
  2198. term.esc = 0;
  2199. break;
  2200. default:
  2201. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2202. (uchar) ascii, isprint(ascii)? ascii:'.');
  2203. term.esc = 0;
  2204. }
  2205. }
  2206. /*
  2207. * All characters which form part of a sequence are not
  2208. * printed
  2209. */
  2210. return;
  2211. }
  2212. /*
  2213. * Display control codes only if we are in graphic mode
  2214. */
  2215. if(control && !(term.c.attr.mode & ATTR_GFX))
  2216. return;
  2217. if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
  2218. selclear(NULL);
  2219. if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2220. term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
  2221. tnewline(1);
  2222. }
  2223. if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
  2224. memmove(&term.line[term.c.y][term.c.x+1],
  2225. &term.line[term.c.y][term.c.x],
  2226. (term.col - term.c.x - 1) * sizeof(Glyph));
  2227. }
  2228. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  2229. if(term.c.x+1 < term.col) {
  2230. tmoveto(term.c.x+1, term.c.y);
  2231. } else {
  2232. term.c.state |= CURSOR_WRAPNEXT;
  2233. }
  2234. }
  2235. int
  2236. tresize(int col, int row) {
  2237. int i;
  2238. int minrow = MIN(row, term.row);
  2239. int mincol = MIN(col, term.col);
  2240. int slide = term.c.y - row + 1;
  2241. bool *bp;
  2242. Line *orig;
  2243. if(col < 1 || row < 1)
  2244. return 0;
  2245. /* free unneeded rows */
  2246. i = 0;
  2247. if(slide > 0) {
  2248. /*
  2249. * slide screen to keep cursor where we expect it -
  2250. * tscrollup would work here, but we can optimize to
  2251. * memmove because we're freeing the earlier lines
  2252. */
  2253. for(/* i = 0 */; i < slide; i++) {
  2254. free(term.line[i]);
  2255. free(term.alt[i]);
  2256. }
  2257. memmove(term.line, term.line + slide, row * sizeof(Line));
  2258. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  2259. }
  2260. for(i += row; i < term.row; i++) {
  2261. free(term.line[i]);
  2262. free(term.alt[i]);
  2263. }
  2264. /* resize to new height */
  2265. term.line = xrealloc(term.line, row * sizeof(Line));
  2266. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2267. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2268. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2269. /* resize each row to new width, zero-pad if needed */
  2270. for(i = 0; i < minrow; i++) {
  2271. term.dirty[i] = 1;
  2272. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2273. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2274. }
  2275. /* allocate any new rows */
  2276. for(/* i == minrow */; i < row; i++) {
  2277. term.dirty[i] = 1;
  2278. term.line[i] = xcalloc(col, sizeof(Glyph));
  2279. term.alt [i] = xcalloc(col, sizeof(Glyph));
  2280. }
  2281. if(col > term.col) {
  2282. bp = term.tabs + term.col;
  2283. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2284. while(--bp > term.tabs && !*bp)
  2285. /* nothing */ ;
  2286. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2287. *bp = 1;
  2288. }
  2289. /* update terminal size */
  2290. term.col = col;
  2291. term.row = row;
  2292. /* reset scrolling region */
  2293. tsetscroll(0, row-1);
  2294. /* make use of the LIMIT in tmoveto */
  2295. tmoveto(term.c.x, term.c.y);
  2296. /* Clearing both screens */
  2297. orig = term.line;
  2298. do {
  2299. if(mincol < col && 0 < minrow) {
  2300. tclearregion(mincol, 0, col - 1, minrow - 1);
  2301. }
  2302. if(0 < col && minrow < row) {
  2303. tclearregion(0, minrow, col - 1, row - 1);
  2304. }
  2305. tswapscreen();
  2306. } while(orig != term.line);
  2307. return (slide > 0);
  2308. }
  2309. void
  2310. xresize(int col, int row) {
  2311. xw.tw = MAX(1, col * xw.cw);
  2312. xw.th = MAX(1, row * xw.ch);
  2313. XFreePixmap(xw.dpy, xw.buf);
  2314. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2315. DefaultDepth(xw.dpy, xw.scr));
  2316. XftDrawChange(xw.draw, xw.buf);
  2317. xclear(0, 0, xw.w, xw.h);
  2318. }
  2319. static inline ushort
  2320. sixd_to_16bit(int x) {
  2321. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  2322. }
  2323. void
  2324. xloadcols(void) {
  2325. int i, r, g, b;
  2326. XRenderColor color = { .alpha = 0xffff };
  2327. static bool loaded;
  2328. Colour *cp;
  2329. if(loaded) {
  2330. for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
  2331. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  2332. }
  2333. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  2334. for(i = 0; i < LEN(colorname); i++) {
  2335. if(!colorname[i])
  2336. continue;
  2337. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
  2338. die("Could not allocate color '%s'\n", colorname[i]);
  2339. }
  2340. }
  2341. /* load colors [16-255] ; same colors as xterm */
  2342. for(i = 16, r = 0; r < 6; r++) {
  2343. for(g = 0; g < 6; g++) {
  2344. for(b = 0; b < 6; b++) {
  2345. color.red = sixd_to_16bit(r);
  2346. color.green = sixd_to_16bit(g);
  2347. color.blue = sixd_to_16bit(b);
  2348. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
  2349. die("Could not allocate color %d\n", i);
  2350. }
  2351. i++;
  2352. }
  2353. }
  2354. }
  2355. for(r = 0; r < 24; r++, i++) {
  2356. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  2357. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
  2358. &dc.col[i])) {
  2359. die("Could not allocate color %d\n", i);
  2360. }
  2361. }
  2362. loaded = true;
  2363. }
  2364. int
  2365. xsetcolorname(int x, const char *name) {
  2366. XRenderColor color = { .alpha = 0xffff };
  2367. Colour colour;
  2368. if (x < 0 || x > LEN(colorname))
  2369. return -1;
  2370. if(!name) {
  2371. if(16 <= x && x < 16 + 216) {
  2372. int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
  2373. color.red = sixd_to_16bit(r);
  2374. color.green = sixd_to_16bit(g);
  2375. color.blue = sixd_to_16bit(b);
  2376. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
  2377. return 0; /* something went wrong */
  2378. dc.col[x] = colour;
  2379. return 1;
  2380. } else if (16 + 216 <= x && x < 256) {
  2381. color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
  2382. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
  2383. return 0; /* something went wrong */
  2384. dc.col[x] = colour;
  2385. return 1;
  2386. } else {
  2387. name = colorname[x];
  2388. }
  2389. }
  2390. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
  2391. return 0;
  2392. dc.col[x] = colour;
  2393. return 1;
  2394. }
  2395. void
  2396. xtermclear(int col1, int row1, int col2, int row2) {
  2397. XftDrawRect(xw.draw,
  2398. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2399. borderpx + col1 * xw.cw,
  2400. borderpx + row1 * xw.ch,
  2401. (col2-col1+1) * xw.cw,
  2402. (row2-row1+1) * xw.ch);
  2403. }
  2404. /*
  2405. * Absolute coordinates.
  2406. */
  2407. void
  2408. xclear(int x1, int y1, int x2, int y2) {
  2409. XftDrawRect(xw.draw,
  2410. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  2411. x1, y1, x2-x1, y2-y1);
  2412. }
  2413. void
  2414. xhints(void) {
  2415. XClassHint class = {opt_class ? opt_class : termname, termname};
  2416. XWMHints wm = {.flags = InputHint, .input = 1};
  2417. XSizeHints *sizeh = NULL;
  2418. sizeh = XAllocSizeHints();
  2419. if(xw.isfixed == False) {
  2420. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2421. sizeh->height = xw.h;
  2422. sizeh->width = xw.w;
  2423. sizeh->height_inc = xw.ch;
  2424. sizeh->width_inc = xw.cw;
  2425. sizeh->base_height = 2 * borderpx;
  2426. sizeh->base_width = 2 * borderpx;
  2427. } else {
  2428. sizeh->flags = PMaxSize | PMinSize;
  2429. sizeh->min_width = sizeh->max_width = xw.fw;
  2430. sizeh->min_height = sizeh->max_height = xw.fh;
  2431. }
  2432. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  2433. XFree(sizeh);
  2434. }
  2435. int
  2436. xloadfont(Font *f, FcPattern *pattern) {
  2437. FcPattern *match;
  2438. FcResult result;
  2439. match = FcFontMatch(NULL, pattern, &result);
  2440. if(!match)
  2441. return 1;
  2442. if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  2443. FcPatternDestroy(match);
  2444. return 1;
  2445. }
  2446. f->set = NULL;
  2447. f->pattern = FcPatternDuplicate(pattern);
  2448. f->ascent = f->match->ascent;
  2449. f->descent = f->match->descent;
  2450. f->lbearing = 0;
  2451. f->rbearing = f->match->max_advance_width;
  2452. f->height = f->ascent + f->descent;
  2453. f->width = f->lbearing + f->rbearing;
  2454. return 0;
  2455. }
  2456. void
  2457. xloadfonts(char *fontstr, int fontsize) {
  2458. FcPattern *pattern;
  2459. FcResult result;
  2460. double fontval;
  2461. if(fontstr[0] == '-') {
  2462. pattern = XftXlfdParse(fontstr, False, False);
  2463. } else {
  2464. pattern = FcNameParse((FcChar8 *)fontstr);
  2465. }
  2466. if(!pattern)
  2467. die("st: can't open font %s\n", fontstr);
  2468. if(fontsize > 0) {
  2469. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2470. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2471. usedfontsize = fontsize;
  2472. } else {
  2473. result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2474. if(result == FcResultMatch) {
  2475. usedfontsize = (int)fontval;
  2476. } else {
  2477. /*
  2478. * Default font size is 12, if none given. This is to
  2479. * have a known usedfontsize value.
  2480. */
  2481. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2482. usedfontsize = 12;
  2483. }
  2484. }
  2485. FcConfigSubstitute(0, pattern, FcMatchPattern);
  2486. FcDefaultSubstitute(pattern);
  2487. if(xloadfont(&dc.font, pattern))
  2488. die("st: can't open font %s\n", fontstr);
  2489. /* Setting character width and height. */
  2490. xw.cw = CEIL(dc.font.width * cwscale);
  2491. xw.ch = CEIL(dc.font.height * chscale);
  2492. FcPatternDel(pattern, FC_SLANT);
  2493. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2494. if(xloadfont(&dc.ifont, pattern))
  2495. die("st: can't open font %s\n", fontstr);
  2496. FcPatternDel(pattern, FC_WEIGHT);
  2497. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2498. if(xloadfont(&dc.ibfont, pattern))
  2499. die("st: can't open font %s\n", fontstr);
  2500. FcPatternDel(pattern, FC_SLANT);
  2501. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  2502. if(xloadfont(&dc.bfont, pattern))
  2503. die("st: can't open font %s\n", fontstr);
  2504. FcPatternDestroy(pattern);
  2505. }
  2506. int
  2507. xloadfontset(Font *f) {
  2508. FcResult result;
  2509. if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
  2510. return 1;
  2511. return 0;
  2512. }
  2513. void
  2514. xunloadfont(Font *f) {
  2515. XftFontClose(xw.dpy, f->match);
  2516. FcPatternDestroy(f->pattern);
  2517. if(f->set)
  2518. FcFontSetDestroy(f->set);
  2519. }
  2520. void
  2521. xunloadfonts(void) {
  2522. int i;
  2523. /* Free the loaded fonts in the font cache. */
  2524. for(i = 0; i < frclen; i++) {
  2525. XftFontClose(xw.dpy, frc[i].font);
  2526. }
  2527. frclen = 0;
  2528. xunloadfont(&dc.font);
  2529. xunloadfont(&dc.bfont);
  2530. xunloadfont(&dc.ifont);
  2531. xunloadfont(&dc.ibfont);
  2532. }
  2533. void
  2534. xzoom(const Arg *arg) {
  2535. xunloadfonts();
  2536. xloadfonts(usedfont, usedfontsize + arg->i);
  2537. cresize(0, 0);
  2538. redraw(0);
  2539. }
  2540. void
  2541. xinit(void) {
  2542. XGCValues gcvalues;
  2543. Cursor cursor;
  2544. Window parent;
  2545. int sw, sh;
  2546. if(!(xw.dpy = XOpenDisplay(NULL)))
  2547. die("Can't open display\n");
  2548. xw.scr = XDefaultScreen(xw.dpy);
  2549. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2550. /* font */
  2551. if(!FcInit())
  2552. die("Could not init fontconfig.\n");
  2553. usedfont = (opt_font == NULL)? font : opt_font;
  2554. xloadfonts(usedfont, 0);
  2555. /* colors */
  2556. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2557. xloadcols();
  2558. /* adjust fixed window geometry */
  2559. if(xw.isfixed) {
  2560. sw = DisplayWidth(xw.dpy, xw.scr);
  2561. sh = DisplayHeight(xw.dpy, xw.scr);
  2562. if(xw.fx < 0)
  2563. xw.fx = sw + xw.fx - xw.fw - 1;
  2564. if(xw.fy < 0)
  2565. xw.fy = sh + xw.fy - xw.fh - 1;
  2566. xw.h = xw.fh;
  2567. xw.w = xw.fw;
  2568. } else {
  2569. /* window - default size */
  2570. xw.h = 2 * borderpx + term.row * xw.ch;
  2571. xw.w = 2 * borderpx + term.col * xw.cw;
  2572. xw.fx = 0;
  2573. xw.fy = 0;
  2574. }
  2575. /* Events */
  2576. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  2577. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  2578. xw.attrs.bit_gravity = NorthWestGravity;
  2579. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  2580. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2581. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2582. xw.attrs.colormap = xw.cmap;
  2583. parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
  2584. XRootWindow(xw.dpy, xw.scr);
  2585. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  2586. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2587. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  2588. | CWEventMask | CWColormap, &xw.attrs);
  2589. memset(&gcvalues, 0, sizeof(gcvalues));
  2590. gcvalues.graphics_exposures = False;
  2591. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  2592. &gcvalues);
  2593. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2594. DefaultDepth(xw.dpy, xw.scr));
  2595. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  2596. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2597. /* Xft rendering context */
  2598. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2599. /* input methods */
  2600. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2601. XSetLocaleModifiers("@im=local");
  2602. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2603. XSetLocaleModifiers("@im=");
  2604. if((xw.xim = XOpenIM(xw.dpy,
  2605. NULL, NULL, NULL)) == NULL) {
  2606. die("XOpenIM failed. Could not open input"
  2607. " device.\n");
  2608. }
  2609. }
  2610. }
  2611. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2612. | XIMStatusNothing, XNClientWindow, xw.win,
  2613. XNFocusWindow, xw.win, NULL);
  2614. if(xw.xic == NULL)
  2615. die("XCreateIC failed. Could not obtain input method.\n");
  2616. /* white cursor, black outline */
  2617. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2618. XDefineCursor(xw.dpy, xw.win, cursor);
  2619. XRecolorCursor(xw.dpy, cursor,
  2620. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2621. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2622. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2623. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2624. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2625. xresettitle();
  2626. XMapWindow(xw.dpy, xw.win);
  2627. xhints();
  2628. XSync(xw.dpy, 0);
  2629. }
  2630. void
  2631. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2632. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2633. width = charlen * xw.cw, xp, i;
  2634. int frcflags;
  2635. int u8fl, u8fblen, u8cblen, doesexist;
  2636. char *u8c, *u8fs;
  2637. long u8char;
  2638. Font *font = &dc.font;
  2639. FcResult fcres;
  2640. FcPattern *fcpattern, *fontpattern;
  2641. FcFontSet *fcsets[] = { NULL };
  2642. FcCharSet *fccharset;
  2643. Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  2644. XRenderColor colfg, colbg;
  2645. Rectangle r;
  2646. int oneatatime;
  2647. frcflags = FRC_NORMAL;
  2648. if(base.mode & ATTR_ITALIC) {
  2649. if(base.fg == defaultfg)
  2650. base.fg = defaultitalic;
  2651. font = &dc.ifont;
  2652. frcflags = FRC_ITALIC;
  2653. } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
  2654. if(base.fg == defaultfg)
  2655. base.fg = defaultitalic;
  2656. font = &dc.ibfont;
  2657. frcflags = FRC_ITALICBOLD;
  2658. } else if(base.mode & ATTR_UNDERLINE) {
  2659. if(base.fg == defaultfg)
  2660. base.fg = defaultunderline;
  2661. }
  2662. if(IS_TRUECOL(base.fg)) {
  2663. colfg.red = TRUERED(base.fg);
  2664. colfg.green = TRUEGREEN(base.fg);
  2665. colfg.blue = TRUEBLUE(base.fg);
  2666. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  2667. fg = &truefg;
  2668. } else {
  2669. fg = &dc.col[base.fg];
  2670. }
  2671. if(IS_TRUECOL(base.bg)) {
  2672. colbg.green = TRUEGREEN(base.bg);
  2673. colbg.red = TRUERED(base.bg);
  2674. colbg.blue = TRUEBLUE(base.bg);
  2675. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  2676. bg = &truebg;
  2677. } else {
  2678. bg = &dc.col[base.bg];
  2679. }
  2680. if(base.mode & ATTR_BOLD) {
  2681. if(BETWEEN(base.fg, 0, 7)) {
  2682. /* basic system colors */
  2683. fg = &dc.col[base.fg + 8];
  2684. } else if(BETWEEN(base.fg, 16, 195)) {
  2685. /* 256 colors */
  2686. fg = &dc.col[base.fg + 36];
  2687. } else if(BETWEEN(base.fg, 232, 251)) {
  2688. /* greyscale */
  2689. fg = &dc.col[base.fg + 4];
  2690. }
  2691. /*
  2692. * Those ranges will not be brightened:
  2693. * 8 - 15 bright system colors
  2694. * 196 - 231 highest 256 color cube
  2695. * 252 - 255 brightest colors in greyscale
  2696. */
  2697. font = &dc.bfont;
  2698. frcflags = FRC_BOLD;
  2699. }
  2700. if(IS_SET(MODE_REVERSE)) {
  2701. if(fg == &dc.col[defaultfg]) {
  2702. fg = &dc.col[defaultbg];
  2703. } else {
  2704. colfg.red = ~fg->color.red;
  2705. colfg.green = ~fg->color.green;
  2706. colfg.blue = ~fg->color.blue;
  2707. colfg.alpha = fg->color.alpha;
  2708. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2709. fg = &revfg;
  2710. }
  2711. if(bg == &dc.col[defaultbg]) {
  2712. bg = &dc.col[defaultfg];
  2713. } else {
  2714. colbg.red = ~bg->color.red;
  2715. colbg.green = ~bg->color.green;
  2716. colbg.blue = ~bg->color.blue;
  2717. colbg.alpha = bg->color.alpha;
  2718. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
  2719. bg = &revbg;
  2720. }
  2721. }
  2722. if(base.mode & ATTR_REVERSE) {
  2723. temp = fg;
  2724. fg = bg;
  2725. bg = temp;
  2726. }
  2727. if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
  2728. fg = bg;
  2729. /* Intelligent cleaning up of the borders. */
  2730. if(x == 0) {
  2731. xclear(0, (y == 0)? 0 : winy, borderpx,
  2732. winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
  2733. }
  2734. if(x + charlen >= term.col) {
  2735. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2736. ((y >= term.row-1)? xw.h : (winy + xw.ch)));
  2737. }
  2738. if(y == 0)
  2739. xclear(winx, 0, winx + width, borderpx);
  2740. if(y == term.row-1)
  2741. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2742. /* Clean up the region we want to draw to. */
  2743. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  2744. /* Set the clip region because Xft is sometimes dirty. */
  2745. r.x = 0;
  2746. r.y = 0;
  2747. r.height = xw.ch;
  2748. r.width = width;
  2749. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  2750. for(xp = winx; bytelen > 0;) {
  2751. /*
  2752. * Search for the range in the to be printed string of glyphs
  2753. * that are in the main font. Then print that range. If
  2754. * some glyph is found that is not in the font, do the
  2755. * fallback dance.
  2756. */
  2757. u8fs = s;
  2758. u8fblen = 0;
  2759. u8fl = 0;
  2760. oneatatime = font->width != xw.cw;
  2761. for(;;) {
  2762. u8c = s;
  2763. u8cblen = utf8decode(s, &u8char);
  2764. s += u8cblen;
  2765. bytelen -= u8cblen;
  2766. doesexist = XftCharExists(xw.dpy, font->match, u8char);
  2767. if(oneatatime || !doesexist || bytelen <= 0) {
  2768. if(oneatatime || bytelen <= 0) {
  2769. if(doesexist) {
  2770. u8fl++;
  2771. u8fblen += u8cblen;
  2772. }
  2773. }
  2774. if(u8fl > 0) {
  2775. XftDrawStringUtf8(xw.draw, fg,
  2776. font->match, xp,
  2777. winy + font->ascent,
  2778. (FcChar8 *)u8fs,
  2779. u8fblen);
  2780. xp += CEIL(font->width * cwscale * u8fl);
  2781. }
  2782. break;
  2783. }
  2784. u8fl++;
  2785. u8fblen += u8cblen;
  2786. }
  2787. if(doesexist) {
  2788. if (oneatatime);
  2789. continue;
  2790. break;
  2791. }
  2792. /* Search the font cache. */
  2793. for(i = 0; i < frclen; i++) {
  2794. if(XftCharExists(xw.dpy, frc[i].font, u8char)
  2795. && frc[i].flags == frcflags) {
  2796. break;
  2797. }
  2798. }
  2799. /* Nothing was found. */
  2800. if(i >= frclen) {
  2801. if(!font->set)
  2802. xloadfontset(font);
  2803. fcsets[0] = font->set;
  2804. /*
  2805. * Nothing was found in the cache. Now use
  2806. * some dozen of Fontconfig calls to get the
  2807. * font for one single character.
  2808. */
  2809. fcpattern = FcPatternDuplicate(font->pattern);
  2810. fccharset = FcCharSetCreate();
  2811. FcCharSetAddChar(fccharset, u8char);
  2812. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  2813. fccharset);
  2814. FcPatternAddBool(fcpattern, FC_SCALABLE,
  2815. FcTrue);
  2816. FcConfigSubstitute(0, fcpattern,
  2817. FcMatchPattern);
  2818. FcDefaultSubstitute(fcpattern);
  2819. fontpattern = FcFontSetMatch(0, fcsets,
  2820. FcTrue, fcpattern, &fcres);
  2821. /*
  2822. * Overwrite or create the new cache entry.
  2823. */
  2824. if(frclen >= LEN(frc)) {
  2825. frclen = LEN(frc) - 1;
  2826. XftFontClose(xw.dpy, frc[frclen].font);
  2827. }
  2828. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  2829. fontpattern);
  2830. frc[frclen].flags = frcflags;
  2831. i = frclen;
  2832. frclen++;
  2833. FcPatternDestroy(fcpattern);
  2834. FcCharSetDestroy(fccharset);
  2835. }
  2836. XftDrawStringUtf8(xw.draw, fg, frc[i].font,
  2837. xp, winy + frc[i].font->ascent,
  2838. (FcChar8 *)u8c, u8cblen);
  2839. xp += CEIL(font->width * cwscale);
  2840. }
  2841. /*
  2842. XftDrawStringUtf8(xw.draw, fg, font->set, winx,
  2843. winy + font->ascent, (FcChar8 *)s, bytelen);
  2844. */
  2845. if(base.mode & ATTR_UNDERLINE) {
  2846. XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
  2847. width, 1);
  2848. }
  2849. /* Reset clip to none. */
  2850. XftDrawSetClip(xw.draw, 0);
  2851. }
  2852. void
  2853. xdrawcursor(void) {
  2854. static int oldx = 0, oldy = 0;
  2855. int sl;
  2856. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
  2857. LIMIT(oldx, 0, term.col-1);
  2858. LIMIT(oldy, 0, term.row-1);
  2859. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  2860. /* remove the old cursor */
  2861. sl = utf8size(term.line[oldy][oldx].c);
  2862. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  2863. oldy, 1, sl);
  2864. /* draw the new one */
  2865. if(!(IS_SET(MODE_HIDE))) {
  2866. if(xw.state & WIN_FOCUSED) {
  2867. if(IS_SET(MODE_REVERSE)) {
  2868. g.mode |= ATTR_REVERSE;
  2869. g.fg = defaultcs;
  2870. g.bg = defaultfg;
  2871. }
  2872. sl = utf8size(g.c);
  2873. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  2874. } else {
  2875. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2876. borderpx + term.c.x * xw.cw,
  2877. borderpx + term.c.y * xw.ch,
  2878. xw.cw - 1, 1);
  2879. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2880. borderpx + term.c.x * xw.cw,
  2881. borderpx + term.c.y * xw.ch,
  2882. 1, xw.ch - 1);
  2883. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2884. borderpx + (term.c.x + 1) * xw.cw - 1,
  2885. borderpx + term.c.y * xw.ch,
  2886. 1, xw.ch - 1);
  2887. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2888. borderpx + term.c.x * xw.cw,
  2889. borderpx + (term.c.y + 1) * xw.ch - 1,
  2890. xw.cw, 1);
  2891. }
  2892. oldx = term.c.x, oldy = term.c.y;
  2893. }
  2894. }
  2895. void
  2896. xsettitle(char *p) {
  2897. XTextProperty prop;
  2898. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  2899. &prop);
  2900. XSetWMName(xw.dpy, xw.win, &prop);
  2901. }
  2902. void
  2903. xresettitle(void) {
  2904. xsettitle(opt_title ? opt_title : "st");
  2905. }
  2906. void
  2907. redraw(int timeout) {
  2908. struct timespec tv = {0, timeout * 1000};
  2909. tfulldirt();
  2910. draw();
  2911. if(timeout > 0) {
  2912. nanosleep(&tv, NULL);
  2913. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2914. }
  2915. }
  2916. void
  2917. draw(void) {
  2918. drawregion(0, 0, term.col, term.row);
  2919. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
  2920. xw.h, 0, 0);
  2921. XSetForeground(xw.dpy, dc.gc,
  2922. dc.col[IS_SET(MODE_REVERSE)?
  2923. defaultfg : defaultbg].pixel);
  2924. }
  2925. void
  2926. drawregion(int x1, int y1, int x2, int y2) {
  2927. int ic, ib, x, y, ox, sl;
  2928. Glyph base, new;
  2929. char buf[DRAW_BUF_SIZ];
  2930. bool ena_sel = sel.ob.x != -1;
  2931. if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
  2932. ena_sel = 0;
  2933. if(!(xw.state & WIN_VISIBLE))
  2934. return;
  2935. for(y = y1; y < y2; y++) {
  2936. if(!term.dirty[y])
  2937. continue;
  2938. xtermclear(0, y, term.col, y);
  2939. term.dirty[y] = 0;
  2940. base = term.line[y][0];
  2941. ic = ib = ox = 0;
  2942. for(x = x1; x < x2; x++) {
  2943. new = term.line[y][x];
  2944. if(ena_sel && selected(x, y))
  2945. new.mode ^= ATTR_REVERSE;
  2946. if(ib > 0 && (ATTRCMP(base, new)
  2947. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  2948. xdraws(buf, base, ox, y, ic, ib);
  2949. ic = ib = 0;
  2950. }
  2951. if(ib == 0) {
  2952. ox = x;
  2953. base = new;
  2954. }
  2955. sl = utf8size(new.c);
  2956. memcpy(buf+ib, new.c, sl);
  2957. ib += sl;
  2958. ++ic;
  2959. }
  2960. if(ib > 0)
  2961. xdraws(buf, base, ox, y, ic, ib);
  2962. }
  2963. xdrawcursor();
  2964. }
  2965. void
  2966. expose(XEvent *ev) {
  2967. XExposeEvent *e = &ev->xexpose;
  2968. if(xw.state & WIN_REDRAW) {
  2969. if(!e->count)
  2970. xw.state &= ~WIN_REDRAW;
  2971. }
  2972. redraw(0);
  2973. }
  2974. void
  2975. visibility(XEvent *ev) {
  2976. XVisibilityEvent *e = &ev->xvisibility;
  2977. if(e->state == VisibilityFullyObscured) {
  2978. xw.state &= ~WIN_VISIBLE;
  2979. } else if(!(xw.state & WIN_VISIBLE)) {
  2980. /* need a full redraw for next Expose, not just a buf copy */
  2981. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2982. }
  2983. }
  2984. void
  2985. unmap(XEvent *ev) {
  2986. xw.state &= ~WIN_VISIBLE;
  2987. }
  2988. void
  2989. xsetpointermotion(int set) {
  2990. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  2991. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  2992. }
  2993. void
  2994. xseturgency(int add) {
  2995. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2996. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2997. XSetWMHints(xw.dpy, xw.win, h);
  2998. XFree(h);
  2999. }
  3000. void
  3001. focus(XEvent *ev) {
  3002. XFocusChangeEvent *e = &ev->xfocus;
  3003. if(e->mode == NotifyGrab)
  3004. return;
  3005. if(ev->type == FocusIn) {
  3006. XSetICFocus(xw.xic);
  3007. xw.state |= WIN_FOCUSED;
  3008. xseturgency(0);
  3009. if(IS_SET(MODE_FOCUS))
  3010. ttywrite("\033[I", 3);
  3011. } else {
  3012. XUnsetICFocus(xw.xic);
  3013. xw.state &= ~WIN_FOCUSED;
  3014. if(IS_SET(MODE_FOCUS))
  3015. ttywrite("\033[O", 3);
  3016. }
  3017. }
  3018. static inline bool
  3019. match(uint mask, uint state) {
  3020. state &= ~ignoremod;
  3021. if(mask == XK_NO_MOD && state)
  3022. return false;
  3023. if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
  3024. return false;
  3025. if(mask == XK_ANY_MOD)
  3026. return true;
  3027. return state == mask;
  3028. }
  3029. void
  3030. numlock(const Arg *dummy) {
  3031. term.numlock ^= 1;
  3032. }
  3033. char*
  3034. kmap(KeySym k, uint state) {
  3035. Key *kp;
  3036. int i;
  3037. /* Check for mapped keys out of X11 function keys. */
  3038. for(i = 0; i < LEN(mappedkeys); i++) {
  3039. if(mappedkeys[i] == k)
  3040. break;
  3041. }
  3042. if(i == LEN(mappedkeys)) {
  3043. if((k & 0xFFFF) < 0xFD00)
  3044. return NULL;
  3045. }
  3046. for(kp = key; kp < key + LEN(key); kp++) {
  3047. if(kp->k != k)
  3048. continue;
  3049. if(!match(kp->mask, state))
  3050. continue;
  3051. if(kp->appkey > 0) {
  3052. if(!IS_SET(MODE_APPKEYPAD))
  3053. continue;
  3054. if(term.numlock && kp->appkey == 2)
  3055. continue;
  3056. } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
  3057. continue;
  3058. }
  3059. if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
  3060. (kp->appcursor > 0
  3061. && !IS_SET(MODE_APPCURSOR))) {
  3062. continue;
  3063. }
  3064. if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
  3065. (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
  3066. continue;
  3067. }
  3068. return kp->s;
  3069. }
  3070. return NULL;
  3071. }
  3072. void
  3073. kpress(XEvent *ev) {
  3074. XKeyEvent *e = &ev->xkey;
  3075. KeySym ksym;
  3076. char xstr[31], buf[32], *customkey, *cp = buf;
  3077. int len, ret;
  3078. long c;
  3079. Status status;
  3080. Shortcut *bp;
  3081. if(IS_SET(MODE_KBDLOCK))
  3082. return;
  3083. len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
  3084. e->state &= ~Mod2Mask;
  3085. /* 1. shortcuts */
  3086. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  3087. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  3088. bp->func(&(bp->arg));
  3089. return;
  3090. }
  3091. }
  3092. /* 2. custom keys from config.h */
  3093. if((customkey = kmap(ksym, e->state))) {
  3094. len = strlen(customkey);
  3095. memcpy(buf, customkey, len);
  3096. /* 3. hardcoded (overrides X lookup) */
  3097. } else {
  3098. if(len == 0)
  3099. return;
  3100. if(len == 1 && e->state & Mod1Mask) {
  3101. if(IS_SET(MODE_8BIT)) {
  3102. if(*xstr < 0177) {
  3103. c = *xstr | 0x80;
  3104. ret = utf8encode(&c, cp);
  3105. cp += ret;
  3106. len = 0;
  3107. }
  3108. } else {
  3109. *cp++ = '\033';
  3110. }
  3111. }
  3112. memcpy(cp, xstr, len);
  3113. len = cp - buf + len;
  3114. }
  3115. ttywrite(buf, len);
  3116. if(IS_SET(MODE_ECHO))
  3117. techo(buf, len);
  3118. }
  3119. void
  3120. cmessage(XEvent *e) {
  3121. /*
  3122. * See xembed specs
  3123. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  3124. */
  3125. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  3126. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  3127. xw.state |= WIN_FOCUSED;
  3128. xseturgency(0);
  3129. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  3130. xw.state &= ~WIN_FOCUSED;
  3131. }
  3132. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  3133. /* Send SIGHUP to shell */
  3134. kill(pid, SIGHUP);
  3135. exit(EXIT_SUCCESS);
  3136. }
  3137. }
  3138. void
  3139. cresize(int width, int height) {
  3140. int col, row;
  3141. if(width != 0)
  3142. xw.w = width;
  3143. if(height != 0)
  3144. xw.h = height;
  3145. col = (xw.w - 2 * borderpx) / xw.cw;
  3146. row = (xw.h - 2 * borderpx) / xw.ch;
  3147. tresize(col, row);
  3148. xresize(col, row);
  3149. ttyresize();
  3150. }
  3151. void
  3152. resize(XEvent *e) {
  3153. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  3154. return;
  3155. cresize(e->xconfigure.width, e->xconfigure.height);
  3156. }
  3157. void
  3158. run(void) {
  3159. XEvent ev;
  3160. int w = xw.w, h = xw.h;
  3161. fd_set rfd;
  3162. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  3163. struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
  3164. /* Waiting for window mapping */
  3165. while(1) {
  3166. XNextEvent(xw.dpy, &ev);
  3167. if(ev.type == ConfigureNotify) {
  3168. w = ev.xconfigure.width;
  3169. h = ev.xconfigure.height;
  3170. } else if(ev.type == MapNotify) {
  3171. break;
  3172. }
  3173. }
  3174. if(!xw.isfixed)
  3175. cresize(w, h);
  3176. else
  3177. cresize(xw.fw, xw.fh);
  3178. ttynew();
  3179. gettimeofday(&lastblink, NULL);
  3180. gettimeofday(&last, NULL);
  3181. for(xev = actionfps;;) {
  3182. FD_ZERO(&rfd);
  3183. FD_SET(cmdfd, &rfd);
  3184. FD_SET(xfd, &rfd);
  3185. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  3186. if(errno == EINTR)
  3187. continue;
  3188. die("select failed: %s\n", SERRNO);
  3189. }
  3190. if(FD_ISSET(cmdfd, &rfd)) {
  3191. ttyread();
  3192. if(blinktimeout) {
  3193. blinkset = tattrset(ATTR_BLINK);
  3194. if(!blinkset && term.mode & ATTR_BLINK)
  3195. term.mode &= ~(MODE_BLINK);
  3196. }
  3197. }
  3198. if(FD_ISSET(xfd, &rfd))
  3199. xev = actionfps;
  3200. gettimeofday(&now, NULL);
  3201. drawtimeout.tv_sec = 0;
  3202. drawtimeout.tv_usec = (1000/xfps) * 1000;
  3203. tv = &drawtimeout;
  3204. dodraw = 0;
  3205. if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  3206. tsetdirtattr(ATTR_BLINK);
  3207. term.mode ^= MODE_BLINK;
  3208. gettimeofday(&lastblink, NULL);
  3209. dodraw = 1;
  3210. }
  3211. if(TIMEDIFF(now, last) \
  3212. > (xev? (1000/xfps) : (1000/actionfps))) {
  3213. dodraw = 1;
  3214. last = now;
  3215. }
  3216. if(dodraw) {
  3217. while(XPending(xw.dpy)) {
  3218. XNextEvent(xw.dpy, &ev);
  3219. if(XFilterEvent(&ev, None))
  3220. continue;
  3221. if(handler[ev.type])
  3222. (handler[ev.type])(&ev);
  3223. }
  3224. draw();
  3225. XFlush(xw.dpy);
  3226. if(xev && !FD_ISSET(xfd, &rfd))
  3227. xev--;
  3228. if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  3229. if(blinkset) {
  3230. if(TIMEDIFF(now, lastblink) \
  3231. > blinktimeout) {
  3232. drawtimeout.tv_usec = 1;
  3233. } else {
  3234. drawtimeout.tv_usec = (1000 * \
  3235. (blinktimeout - \
  3236. TIMEDIFF(now,
  3237. lastblink)));
  3238. }
  3239. } else {
  3240. tv = NULL;
  3241. }
  3242. }
  3243. }
  3244. }
  3245. }
  3246. void
  3247. usage(void) {
  3248. die("%s " VERSION " (c) 2010-2013 st engineers\n" \
  3249. "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
  3250. " [-t title] [-w windowid] [-e command ...]\n", argv0);
  3251. }
  3252. int
  3253. main(int argc, char *argv[]) {
  3254. int bitm, xr, yr;
  3255. uint wr, hr;
  3256. char *titles;
  3257. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  3258. xw.isfixed = False;
  3259. ARGBEGIN {
  3260. case 'a':
  3261. allowaltscreen = false;
  3262. break;
  3263. case 'c':
  3264. opt_class = EARGF(usage());
  3265. break;
  3266. case 'e':
  3267. /* eat all remaining arguments */
  3268. if(argc > 1) {
  3269. opt_cmd = &argv[1];
  3270. if(argv[1] != NULL && opt_title == NULL) {
  3271. titles = strdup(argv[1]);
  3272. opt_title = basename(titles);
  3273. }
  3274. }
  3275. goto run;
  3276. case 'f':
  3277. opt_font = EARGF(usage());
  3278. break;
  3279. case 'g':
  3280. bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
  3281. if(bitm & XValue)
  3282. xw.fx = xr;
  3283. if(bitm & YValue)
  3284. xw.fy = yr;
  3285. if(bitm & WidthValue)
  3286. xw.fw = (int)wr;
  3287. if(bitm & HeightValue)
  3288. xw.fh = (int)hr;
  3289. if(bitm & XNegative && xw.fx == 0)
  3290. xw.fx = -1;
  3291. if(bitm & XNegative && xw.fy == 0)
  3292. xw.fy = -1;
  3293. if(xw.fh != 0 && xw.fw != 0)
  3294. xw.isfixed = True;
  3295. break;
  3296. case 'o':
  3297. opt_io = EARGF(usage());
  3298. break;
  3299. case 't':
  3300. opt_title = EARGF(usage());
  3301. break;
  3302. case 'w':
  3303. opt_embed = EARGF(usage());
  3304. break;
  3305. case 'v':
  3306. default:
  3307. usage();
  3308. } ARGEND;
  3309. run:
  3310. setlocale(LC_CTYPE, "");
  3311. XSetLocaleModifiers("");
  3312. tnew(80, 24);
  3313. xinit();
  3314. selinit();
  3315. run();
  3316. return 0;
  3317. }