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.

3870 lines
85 KiB

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