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.

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