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.

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