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.

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