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.

3889 lines
85 KiB

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