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.

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