Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3867 lines
84 KiB

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