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.

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