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.

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