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.

3957 lines
87 KiB

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