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.

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