My build of suckless st terminal
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.

3794 lines
82 KiB

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