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.

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