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.

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