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.

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