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.

3809 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 && x > 0 && !((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 'n': /* DSR – Device Status Report (cursor position) */
  1839. if (csiescseq.arg[0] == 6) {
  1840. char buf[40];
  1841. int len = snprintf(buf, sizeof(buf),"\033[%i;%iR", term.c.y+1, term.c.x+1);
  1842. ttywrite(buf, len);
  1843. break;
  1844. }
  1845. case 'r': /* DECSTBM -- Set Scrolling Region */
  1846. if(csiescseq.priv) {
  1847. goto unknown;
  1848. } else {
  1849. DEFAULT(csiescseq.arg[0], 1);
  1850. DEFAULT(csiescseq.arg[1], term.row);
  1851. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1852. tmoveato(0, 0);
  1853. }
  1854. break;
  1855. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1856. tcursor(CURSOR_SAVE);
  1857. break;
  1858. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1859. tcursor(CURSOR_LOAD);
  1860. break;
  1861. }
  1862. }
  1863. void
  1864. csidump(void) {
  1865. int i;
  1866. uint c;
  1867. printf("ESC[");
  1868. for(i = 0; i < csiescseq.len; i++) {
  1869. c = csiescseq.buf[i] & 0xff;
  1870. if(isprint(c)) {
  1871. putchar(c);
  1872. } else if(c == '\n') {
  1873. printf("(\\n)");
  1874. } else if(c == '\r') {
  1875. printf("(\\r)");
  1876. } else if(c == 0x1b) {
  1877. printf("(\\e)");
  1878. } else {
  1879. printf("(%02x)", c);
  1880. }
  1881. }
  1882. putchar('\n');
  1883. }
  1884. void
  1885. csireset(void) {
  1886. memset(&csiescseq, 0, sizeof(csiescseq));
  1887. }
  1888. void
  1889. strhandle(void) {
  1890. char *p = NULL;
  1891. int i, j, narg;
  1892. strparse();
  1893. narg = strescseq.narg;
  1894. switch(strescseq.type) {
  1895. case ']': /* OSC -- Operating System Command */
  1896. switch(i = atoi(strescseq.args[0])) {
  1897. case 0:
  1898. case 1:
  1899. case 2:
  1900. if(narg > 1)
  1901. xsettitle(strescseq.args[1]);
  1902. break;
  1903. case 4: /* color set */
  1904. if(narg < 3)
  1905. break;
  1906. p = strescseq.args[2];
  1907. /* fall through */
  1908. case 104: /* color reset, here p = NULL */
  1909. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  1910. if (!xsetcolorname(j, p)) {
  1911. fprintf(stderr, "erresc: invalid color %s\n", p);
  1912. } else {
  1913. /*
  1914. * TODO if defaultbg color is changed, borders
  1915. * are dirty
  1916. */
  1917. redraw(0);
  1918. }
  1919. break;
  1920. default:
  1921. fprintf(stderr, "erresc: unknown str ");
  1922. strdump();
  1923. break;
  1924. }
  1925. break;
  1926. case 'k': /* old title set compatibility */
  1927. xsettitle(strescseq.args[0]);
  1928. break;
  1929. case 'P': /* DSC -- Device Control String */
  1930. case '_': /* APC -- Application Program Command */
  1931. case '^': /* PM -- Privacy Message */
  1932. default:
  1933. fprintf(stderr, "erresc: unknown str ");
  1934. strdump();
  1935. /* die(""); */
  1936. break;
  1937. }
  1938. }
  1939. void
  1940. strparse(void) {
  1941. char *p = strescseq.buf;
  1942. strescseq.narg = 0;
  1943. strescseq.buf[strescseq.len] = '\0';
  1944. while(p && strescseq.narg < STR_ARG_SIZ)
  1945. strescseq.args[strescseq.narg++] = strsep(&p, ";");
  1946. }
  1947. void
  1948. strdump(void) {
  1949. int i;
  1950. uint c;
  1951. printf("ESC%c", strescseq.type);
  1952. for(i = 0; i < strescseq.len; i++) {
  1953. c = strescseq.buf[i] & 0xff;
  1954. if(c == '\0') {
  1955. return;
  1956. } else if(isprint(c)) {
  1957. putchar(c);
  1958. } else if(c == '\n') {
  1959. printf("(\\n)");
  1960. } else if(c == '\r') {
  1961. printf("(\\r)");
  1962. } else if(c == 0x1b) {
  1963. printf("(\\e)");
  1964. } else {
  1965. printf("(%02x)", c);
  1966. }
  1967. }
  1968. printf("ESC\\\n");
  1969. }
  1970. void
  1971. strreset(void) {
  1972. memset(&strescseq, 0, sizeof(strescseq));
  1973. }
  1974. void
  1975. tputtab(bool forward) {
  1976. uint x = term.c.x;
  1977. if(forward) {
  1978. if(x == term.col)
  1979. return;
  1980. for(++x; x < term.col && !term.tabs[x]; ++x)
  1981. /* nothing */ ;
  1982. } else {
  1983. if(x == 0)
  1984. return;
  1985. for(--x; x > 0 && !term.tabs[x]; --x)
  1986. /* nothing */ ;
  1987. }
  1988. tmoveto(x, term.c.y);
  1989. }
  1990. void
  1991. techo(char *buf, int len) {
  1992. for(; len > 0; buf++, len--) {
  1993. char c = *buf;
  1994. if(c == '\033') { /* escape */
  1995. tputc("^", 1);
  1996. tputc("[", 1);
  1997. } else if(c < '\x20') { /* control code */
  1998. if(c != '\n' && c != '\r' && c != '\t') {
  1999. c |= '\x40';
  2000. tputc("^", 1);
  2001. }
  2002. tputc(&c, 1);
  2003. } else {
  2004. break;
  2005. }
  2006. }
  2007. if(len)
  2008. tputc(buf, len);
  2009. }
  2010. void
  2011. tputc(char *c, int len) {
  2012. uchar ascii = *c;
  2013. bool control = ascii < '\x20' || ascii == 0177;
  2014. long u8char;
  2015. int width;
  2016. if(len == 1) {
  2017. width = 1;
  2018. } else {
  2019. utf8decode(c, &u8char);
  2020. width = wcwidth(u8char);
  2021. }
  2022. if(iofd != -1) {
  2023. if(xwrite(iofd, c, len) < 0) {
  2024. fprintf(stderr, "Error writing in %s:%s\n",
  2025. opt_io, strerror(errno));
  2026. close(iofd);
  2027. iofd = -1;
  2028. }
  2029. }
  2030. /*
  2031. * STR sequences must be checked before anything else
  2032. * because it can use some control codes as part of the sequence.
  2033. */
  2034. if(term.esc & ESC_STR) {
  2035. switch(ascii) {
  2036. case '\033':
  2037. term.esc = ESC_START | ESC_STR_END;
  2038. break;
  2039. case '\a': /* backwards compatibility to xterm */
  2040. term.esc = 0;
  2041. strhandle();
  2042. break;
  2043. default:
  2044. if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
  2045. memmove(&strescseq.buf[strescseq.len], c, len);
  2046. strescseq.len += len;
  2047. } else {
  2048. /*
  2049. * Here is a bug in terminals. If the user never sends
  2050. * some code to stop the str or esc command, then st
  2051. * will stop responding. But this is better than
  2052. * silently failing with unknown characters. At least
  2053. * then users will report back.
  2054. *
  2055. * In the case users ever get fixed, here is the code:
  2056. */
  2057. /*
  2058. * term.esc = 0;
  2059. * strhandle();
  2060. */
  2061. }
  2062. }
  2063. return;
  2064. }
  2065. /*
  2066. * Actions of control codes must be performed as soon they arrive
  2067. * because they can be embedded inside a control sequence, and
  2068. * they must not cause conflicts with sequences.
  2069. */
  2070. if(control) {
  2071. switch(ascii) {
  2072. case '\t': /* HT */
  2073. tputtab(1);
  2074. return;
  2075. case '\b': /* BS */
  2076. tmoveto(term.c.x-1, term.c.y);
  2077. return;
  2078. case '\r': /* CR */
  2079. tmoveto(0, term.c.y);
  2080. return;
  2081. case '\f': /* LF */
  2082. case '\v': /* VT */
  2083. case '\n': /* LF */
  2084. /* go to first col if the mode is set */
  2085. tnewline(IS_SET(MODE_CRLF));
  2086. return;
  2087. case '\a': /* BEL */
  2088. if(!(xw.state & WIN_FOCUSED))
  2089. xseturgency(1);
  2090. if (bellvolume)
  2091. XBell(xw.dpy, bellvolume);
  2092. return;
  2093. case '\033': /* ESC */
  2094. csireset();
  2095. term.esc = ESC_START;
  2096. return;
  2097. case '\016': /* SO */
  2098. case '\017': /* SI */
  2099. /*
  2100. * Different charsets are hard to handle. Applications
  2101. * should use the right alt charset escapes for the
  2102. * only reason they still exist: line drawing. The
  2103. * rest is incompatible history st should not support.
  2104. */
  2105. return;
  2106. case '\032': /* SUB */
  2107. case '\030': /* CAN */
  2108. csireset();
  2109. return;
  2110. case '\005': /* ENQ (IGNORED) */
  2111. case '\000': /* NUL (IGNORED) */
  2112. case '\021': /* XON (IGNORED) */
  2113. case '\023': /* XOFF (IGNORED) */
  2114. case 0177: /* DEL (IGNORED) */
  2115. return;
  2116. }
  2117. } else if(term.esc & ESC_START) {
  2118. if(term.esc & ESC_CSI) {
  2119. csiescseq.buf[csiescseq.len++] = ascii;
  2120. if(BETWEEN(ascii, 0x40, 0x7E)
  2121. || csiescseq.len >= \
  2122. sizeof(csiescseq.buf)-1) {
  2123. term.esc = 0;
  2124. csiparse();
  2125. csihandle();
  2126. }
  2127. } else if(term.esc & ESC_STR_END) {
  2128. term.esc = 0;
  2129. if(ascii == '\\')
  2130. strhandle();
  2131. } else if(term.esc & ESC_ALTCHARSET) {
  2132. switch(ascii) {
  2133. case '0': /* Line drawing set */
  2134. term.c.attr.mode |= ATTR_GFX;
  2135. break;
  2136. case 'B': /* USASCII */
  2137. term.c.attr.mode &= ~ATTR_GFX;
  2138. break;
  2139. case 'A': /* UK (IGNORED) */
  2140. case '<': /* multinational charset (IGNORED) */
  2141. case '5': /* Finnish (IGNORED) */
  2142. case 'C': /* Finnish (IGNORED) */
  2143. case 'K': /* German (IGNORED) */
  2144. break;
  2145. default:
  2146. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  2147. }
  2148. term.esc = 0;
  2149. } else if(term.esc & ESC_TEST) {
  2150. if(ascii == '8') { /* DEC screen alignment test. */
  2151. char E[UTF_SIZ] = "E";
  2152. int x, y;
  2153. for(x = 0; x < term.col; ++x) {
  2154. for(y = 0; y < term.row; ++y)
  2155. tsetchar(E, &term.c.attr, x, y);
  2156. }
  2157. }
  2158. term.esc = 0;
  2159. } else {
  2160. switch(ascii) {
  2161. case '[':
  2162. term.esc |= ESC_CSI;
  2163. break;
  2164. case '#':
  2165. term.esc |= ESC_TEST;
  2166. break;
  2167. case 'P': /* DCS -- Device Control String */
  2168. case '_': /* APC -- Application Program Command */
  2169. case '^': /* PM -- Privacy Message */
  2170. case ']': /* OSC -- Operating System Command */
  2171. case 'k': /* old title set compatibility */
  2172. strreset();
  2173. strescseq.type = ascii;
  2174. term.esc |= ESC_STR;
  2175. break;
  2176. case '(': /* set primary charset G0 */
  2177. term.esc |= ESC_ALTCHARSET;
  2178. break;
  2179. case ')': /* set secondary charset G1 (IGNORED) */
  2180. case '*': /* set tertiary charset G2 (IGNORED) */
  2181. case '+': /* set quaternary charset G3 (IGNORED) */
  2182. term.esc = 0;
  2183. break;
  2184. case 'D': /* IND -- Linefeed */
  2185. if(term.c.y == term.bot) {
  2186. tscrollup(term.top, 1);
  2187. } else {
  2188. tmoveto(term.c.x, term.c.y+1);
  2189. }
  2190. term.esc = 0;
  2191. break;
  2192. case 'E': /* NEL -- Next line */
  2193. tnewline(1); /* always go to first col */
  2194. term.esc = 0;
  2195. break;
  2196. case 'H': /* HTS -- Horizontal tab stop */
  2197. term.tabs[term.c.x] = 1;
  2198. term.esc = 0;
  2199. break;
  2200. case 'M': /* RI -- Reverse index */
  2201. if(term.c.y == term.top) {
  2202. tscrolldown(term.top, 1);
  2203. } else {
  2204. tmoveto(term.c.x, term.c.y-1);
  2205. }
  2206. term.esc = 0;
  2207. break;
  2208. case 'Z': /* DECID -- Identify Terminal */
  2209. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  2210. term.esc = 0;
  2211. break;
  2212. case 'c': /* RIS -- Reset to inital state */
  2213. treset();
  2214. term.esc = 0;
  2215. xresettitle();
  2216. xloadcols();
  2217. break;
  2218. case '=': /* DECPAM -- Application keypad */
  2219. term.mode |= MODE_APPKEYPAD;
  2220. term.esc = 0;
  2221. break;
  2222. case '>': /* DECPNM -- Normal keypad */
  2223. term.mode &= ~MODE_APPKEYPAD;
  2224. term.esc = 0;
  2225. break;
  2226. case '7': /* DECSC -- Save Cursor */
  2227. tcursor(CURSOR_SAVE);
  2228. term.esc = 0;
  2229. break;
  2230. case '8': /* DECRC -- Restore Cursor */
  2231. tcursor(CURSOR_LOAD);
  2232. term.esc = 0;
  2233. break;
  2234. case '\\': /* ST -- Stop */
  2235. term.esc = 0;
  2236. break;
  2237. default:
  2238. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2239. (uchar) ascii, isprint(ascii)? ascii:'.');
  2240. term.esc = 0;
  2241. }
  2242. }
  2243. /*
  2244. * All characters which form part of a sequence are not
  2245. * printed
  2246. */
  2247. return;
  2248. }
  2249. /*
  2250. * Display control codes only if we are in graphic mode
  2251. */
  2252. if(control && !(term.c.attr.mode & ATTR_GFX))
  2253. return;
  2254. if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
  2255. selclear(NULL);
  2256. if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2257. term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
  2258. tnewline(1);
  2259. }
  2260. if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
  2261. memmove(&term.line[term.c.y][term.c.x+1],
  2262. &term.line[term.c.y][term.c.x],
  2263. (term.col - term.c.x - 1) * sizeof(Glyph));
  2264. }
  2265. if(term.c.x+width > term.col)
  2266. tnewline(1);
  2267. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  2268. if(width == 2) {
  2269. term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
  2270. if(term.c.x+1 < term.col) {
  2271. term.line[term.c.y][term.c.x+1].c[0] = '\0';
  2272. term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
  2273. }
  2274. }
  2275. if(term.c.x+width < term.col) {
  2276. tmoveto(term.c.x+width, term.c.y);
  2277. } else {
  2278. term.c.state |= CURSOR_WRAPNEXT;
  2279. }
  2280. }
  2281. int
  2282. tresize(int col, int row) {
  2283. int i;
  2284. int minrow = MIN(row, term.row);
  2285. int mincol = MIN(col, term.col);
  2286. int slide = term.c.y - row + 1;
  2287. bool *bp;
  2288. Line *orig;
  2289. if(col < 1 || row < 1)
  2290. return 0;
  2291. /* free unneeded rows */
  2292. i = 0;
  2293. if(slide > 0) {
  2294. /*
  2295. * slide screen to keep cursor where we expect it -
  2296. * tscrollup would work here, but we can optimize to
  2297. * memmove because we're freeing the earlier lines
  2298. */
  2299. for(/* i = 0 */; i < slide; i++) {
  2300. free(term.line[i]);
  2301. free(term.alt[i]);
  2302. }
  2303. memmove(term.line, term.line + slide, row * sizeof(Line));
  2304. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  2305. }
  2306. for(i += row; i < term.row; i++) {
  2307. free(term.line[i]);
  2308. free(term.alt[i]);
  2309. }
  2310. /* resize to new height */
  2311. term.line = xrealloc(term.line, row * sizeof(Line));
  2312. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2313. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2314. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2315. /* resize each row to new width, zero-pad if needed */
  2316. for(i = 0; i < minrow; i++) {
  2317. term.dirty[i] = 1;
  2318. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2319. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2320. }
  2321. /* allocate any new rows */
  2322. for(/* i == minrow */; i < row; i++) {
  2323. term.dirty[i] = 1;
  2324. term.line[i] = xmalloc(col * sizeof(Glyph));
  2325. term.alt[i] = xmalloc(col * sizeof(Glyph));
  2326. }
  2327. if(col > term.col) {
  2328. bp = term.tabs + term.col;
  2329. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2330. while(--bp > term.tabs && !*bp)
  2331. /* nothing */ ;
  2332. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2333. *bp = 1;
  2334. }
  2335. /* update terminal size */
  2336. term.col = col;
  2337. term.row = row;
  2338. /* reset scrolling region */
  2339. tsetscroll(0, row-1);
  2340. /* make use of the LIMIT in tmoveto */
  2341. tmoveto(term.c.x, term.c.y);
  2342. /* Clearing both screens */
  2343. orig = term.line;
  2344. do {
  2345. if(mincol < col && 0 < minrow) {
  2346. tclearregion(mincol, 0, col - 1, minrow - 1);
  2347. }
  2348. if(0 < col && minrow < row) {
  2349. tclearregion(0, minrow, col - 1, row - 1);
  2350. }
  2351. tswapscreen();
  2352. } while(orig != term.line);
  2353. return (slide > 0);
  2354. }
  2355. void
  2356. xresize(int col, int row) {
  2357. xw.tw = MAX(1, col * xw.cw);
  2358. xw.th = MAX(1, row * xw.ch);
  2359. XFreePixmap(xw.dpy, xw.buf);
  2360. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2361. DefaultDepth(xw.dpy, xw.scr));
  2362. XftDrawChange(xw.draw, xw.buf);
  2363. xclear(0, 0, xw.w, xw.h);
  2364. }
  2365. static inline ushort
  2366. sixd_to_16bit(int x) {
  2367. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  2368. }
  2369. void
  2370. xloadcols(void) {
  2371. int i, r, g, b;
  2372. XRenderColor color = { .alpha = 0xffff };
  2373. static bool loaded;
  2374. Colour *cp;
  2375. if(loaded) {
  2376. for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
  2377. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  2378. }
  2379. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  2380. for(i = 0; i < LEN(colorname); i++) {
  2381. if(!colorname[i])
  2382. continue;
  2383. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
  2384. die("Could not allocate color '%s'\n", colorname[i]);
  2385. }
  2386. }
  2387. /* load colors [16-255] ; same colors as xterm */
  2388. for(i = 16, r = 0; r < 6; r++) {
  2389. for(g = 0; g < 6; g++) {
  2390. for(b = 0; b < 6; b++) {
  2391. color.red = sixd_to_16bit(r);
  2392. color.green = sixd_to_16bit(g);
  2393. color.blue = sixd_to_16bit(b);
  2394. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
  2395. die("Could not allocate color %d\n", i);
  2396. }
  2397. i++;
  2398. }
  2399. }
  2400. }
  2401. for(r = 0; r < 24; r++, i++) {
  2402. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  2403. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
  2404. &dc.col[i])) {
  2405. die("Could not allocate color %d\n", i);
  2406. }
  2407. }
  2408. loaded = true;
  2409. }
  2410. int
  2411. xsetcolorname(int x, const char *name) {
  2412. XRenderColor color = { .alpha = 0xffff };
  2413. Colour colour;
  2414. if (x < 0 || x > LEN(colorname))
  2415. return -1;
  2416. if(!name) {
  2417. if(16 <= x && x < 16 + 216) {
  2418. int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
  2419. color.red = sixd_to_16bit(r);
  2420. color.green = sixd_to_16bit(g);
  2421. color.blue = sixd_to_16bit(b);
  2422. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
  2423. return 0; /* something went wrong */
  2424. dc.col[x] = colour;
  2425. return 1;
  2426. } else if (16 + 216 <= x && x < 256) {
  2427. color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
  2428. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
  2429. return 0; /* something went wrong */
  2430. dc.col[x] = colour;
  2431. return 1;
  2432. } else {
  2433. name = colorname[x];
  2434. }
  2435. }
  2436. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
  2437. return 0;
  2438. dc.col[x] = colour;
  2439. return 1;
  2440. }
  2441. void
  2442. xtermclear(int col1, int row1, int col2, int row2) {
  2443. XftDrawRect(xw.draw,
  2444. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2445. borderpx + col1 * xw.cw,
  2446. borderpx + row1 * xw.ch,
  2447. (col2-col1+1) * xw.cw,
  2448. (row2-row1+1) * xw.ch);
  2449. }
  2450. /*
  2451. * Absolute coordinates.
  2452. */
  2453. void
  2454. xclear(int x1, int y1, int x2, int y2) {
  2455. XftDrawRect(xw.draw,
  2456. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  2457. x1, y1, x2-x1, y2-y1);
  2458. }
  2459. void
  2460. xhints(void) {
  2461. XClassHint class = {opt_class ? opt_class : termname, termname};
  2462. XWMHints wm = {.flags = InputHint, .input = 1};
  2463. XSizeHints *sizeh = NULL;
  2464. sizeh = XAllocSizeHints();
  2465. if(xw.isfixed == False) {
  2466. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2467. sizeh->height = xw.h;
  2468. sizeh->width = xw.w;
  2469. sizeh->height_inc = xw.ch;
  2470. sizeh->width_inc = xw.cw;
  2471. sizeh->base_height = 2 * borderpx;
  2472. sizeh->base_width = 2 * borderpx;
  2473. } else {
  2474. sizeh->flags = PMaxSize | PMinSize;
  2475. sizeh->min_width = sizeh->max_width = xw.fw;
  2476. sizeh->min_height = sizeh->max_height = xw.fh;
  2477. }
  2478. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  2479. XFree(sizeh);
  2480. }
  2481. int
  2482. xloadfont(Font *f, FcPattern *pattern) {
  2483. FcPattern *match;
  2484. FcResult result;
  2485. match = FcFontMatch(NULL, pattern, &result);
  2486. if(!match)
  2487. return 1;
  2488. if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  2489. FcPatternDestroy(match);
  2490. return 1;
  2491. }
  2492. f->set = NULL;
  2493. f->pattern = FcPatternDuplicate(pattern);
  2494. f->ascent = f->match->ascent;
  2495. f->descent = f->match->descent;
  2496. f->lbearing = 0;
  2497. f->rbearing = f->match->max_advance_width;
  2498. f->height = f->ascent + f->descent;
  2499. f->width = f->lbearing + f->rbearing;
  2500. return 0;
  2501. }
  2502. void
  2503. xloadfonts(char *fontstr, int fontsize) {
  2504. FcPattern *pattern;
  2505. FcResult result;
  2506. double fontval;
  2507. if(fontstr[0] == '-') {
  2508. pattern = XftXlfdParse(fontstr, False, False);
  2509. } else {
  2510. pattern = FcNameParse((FcChar8 *)fontstr);
  2511. }
  2512. if(!pattern)
  2513. die("st: can't open font %s\n", fontstr);
  2514. if(fontsize > 0) {
  2515. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2516. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2517. usedfontsize = fontsize;
  2518. } else {
  2519. result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2520. if(result == FcResultMatch) {
  2521. usedfontsize = (int)fontval;
  2522. } else {
  2523. /*
  2524. * Default font size is 12, if none given. This is to
  2525. * have a known usedfontsize value.
  2526. */
  2527. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2528. usedfontsize = 12;
  2529. }
  2530. }
  2531. FcConfigSubstitute(0, pattern, FcMatchPattern);
  2532. FcDefaultSubstitute(pattern);
  2533. if(xloadfont(&dc.font, pattern))
  2534. die("st: can't open font %s\n", fontstr);
  2535. /* Setting character width and height. */
  2536. xw.cw = CEIL(dc.font.width * cwscale);
  2537. xw.ch = CEIL(dc.font.height * chscale);
  2538. FcPatternDel(pattern, FC_SLANT);
  2539. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2540. if(xloadfont(&dc.ifont, pattern))
  2541. die("st: can't open font %s\n", fontstr);
  2542. FcPatternDel(pattern, FC_WEIGHT);
  2543. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2544. if(xloadfont(&dc.ibfont, pattern))
  2545. die("st: can't open font %s\n", fontstr);
  2546. FcPatternDel(pattern, FC_SLANT);
  2547. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  2548. if(xloadfont(&dc.bfont, pattern))
  2549. die("st: can't open font %s\n", fontstr);
  2550. FcPatternDestroy(pattern);
  2551. }
  2552. int
  2553. xloadfontset(Font *f) {
  2554. FcResult result;
  2555. if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
  2556. return 1;
  2557. return 0;
  2558. }
  2559. void
  2560. xunloadfont(Font *f) {
  2561. XftFontClose(xw.dpy, f->match);
  2562. FcPatternDestroy(f->pattern);
  2563. if(f->set)
  2564. FcFontSetDestroy(f->set);
  2565. }
  2566. void
  2567. xunloadfonts(void) {
  2568. int i;
  2569. /* Free the loaded fonts in the font cache. */
  2570. for(i = 0; i < frclen; i++) {
  2571. XftFontClose(xw.dpy, frc[i].font);
  2572. }
  2573. frclen = 0;
  2574. xunloadfont(&dc.font);
  2575. xunloadfont(&dc.bfont);
  2576. xunloadfont(&dc.ifont);
  2577. xunloadfont(&dc.ibfont);
  2578. }
  2579. void
  2580. xzoom(const Arg *arg) {
  2581. xunloadfonts();
  2582. xloadfonts(usedfont, usedfontsize + arg->i);
  2583. cresize(0, 0);
  2584. redraw(0);
  2585. }
  2586. void
  2587. xinit(void) {
  2588. XGCValues gcvalues;
  2589. Cursor cursor;
  2590. Window parent;
  2591. int sw, sh;
  2592. if(!(xw.dpy = XOpenDisplay(NULL)))
  2593. die("Can't open display\n");
  2594. xw.scr = XDefaultScreen(xw.dpy);
  2595. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2596. /* font */
  2597. if(!FcInit())
  2598. die("Could not init fontconfig.\n");
  2599. usedfont = (opt_font == NULL)? font : opt_font;
  2600. xloadfonts(usedfont, 0);
  2601. /* colors */
  2602. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2603. xloadcols();
  2604. /* adjust fixed window geometry */
  2605. if(xw.isfixed) {
  2606. sw = DisplayWidth(xw.dpy, xw.scr);
  2607. sh = DisplayHeight(xw.dpy, xw.scr);
  2608. if(xw.fx < 0)
  2609. xw.fx = sw + xw.fx - xw.fw - 1;
  2610. if(xw.fy < 0)
  2611. xw.fy = sh + xw.fy - xw.fh - 1;
  2612. xw.h = xw.fh;
  2613. xw.w = xw.fw;
  2614. } else {
  2615. /* window - default size */
  2616. xw.h = 2 * borderpx + term.row * xw.ch;
  2617. xw.w = 2 * borderpx + term.col * xw.cw;
  2618. xw.fx = 0;
  2619. xw.fy = 0;
  2620. }
  2621. /* Events */
  2622. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  2623. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  2624. xw.attrs.bit_gravity = NorthWestGravity;
  2625. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  2626. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2627. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2628. xw.attrs.colormap = xw.cmap;
  2629. parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
  2630. XRootWindow(xw.dpy, xw.scr);
  2631. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  2632. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2633. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  2634. | CWEventMask | CWColormap, &xw.attrs);
  2635. memset(&gcvalues, 0, sizeof(gcvalues));
  2636. gcvalues.graphics_exposures = False;
  2637. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  2638. &gcvalues);
  2639. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2640. DefaultDepth(xw.dpy, xw.scr));
  2641. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  2642. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2643. /* Xft rendering context */
  2644. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2645. /* input methods */
  2646. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2647. XSetLocaleModifiers("@im=local");
  2648. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2649. XSetLocaleModifiers("@im=");
  2650. if((xw.xim = XOpenIM(xw.dpy,
  2651. NULL, NULL, NULL)) == NULL) {
  2652. die("XOpenIM failed. Could not open input"
  2653. " device.\n");
  2654. }
  2655. }
  2656. }
  2657. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2658. | XIMStatusNothing, XNClientWindow, xw.win,
  2659. XNFocusWindow, xw.win, NULL);
  2660. if(xw.xic == NULL)
  2661. die("XCreateIC failed. Could not obtain input method.\n");
  2662. /* white cursor, black outline */
  2663. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2664. XDefineCursor(xw.dpy, xw.win, cursor);
  2665. XRecolorCursor(xw.dpy, cursor,
  2666. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2667. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2668. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2669. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2670. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2671. xresettitle();
  2672. XMapWindow(xw.dpy, xw.win);
  2673. xhints();
  2674. XSync(xw.dpy, 0);
  2675. }
  2676. void
  2677. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2678. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2679. width = charlen * xw.cw, xp, i;
  2680. int frcflags;
  2681. int u8fl, u8fblen, u8cblen, doesexist;
  2682. char *u8c, *u8fs;
  2683. long u8char;
  2684. Font *font = &dc.font;
  2685. FcResult fcres;
  2686. FcPattern *fcpattern, *fontpattern;
  2687. FcFontSet *fcsets[] = { NULL };
  2688. FcCharSet *fccharset;
  2689. Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  2690. XRenderColor colfg, colbg;
  2691. Rectangle r;
  2692. int oneatatime;
  2693. frcflags = FRC_NORMAL;
  2694. if(base.mode & ATTR_ITALIC) {
  2695. if(base.fg == defaultfg)
  2696. base.fg = defaultitalic;
  2697. font = &dc.ifont;
  2698. frcflags = FRC_ITALIC;
  2699. } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
  2700. if(base.fg == defaultfg)
  2701. base.fg = defaultitalic;
  2702. font = &dc.ibfont;
  2703. frcflags = FRC_ITALICBOLD;
  2704. } else if(base.mode & ATTR_UNDERLINE) {
  2705. if(base.fg == defaultfg)
  2706. base.fg = defaultunderline;
  2707. }
  2708. if(IS_TRUECOL(base.fg)) {
  2709. colfg.red = TRUERED(base.fg);
  2710. colfg.green = TRUEGREEN(base.fg);
  2711. colfg.blue = TRUEBLUE(base.fg);
  2712. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  2713. fg = &truefg;
  2714. } else {
  2715. fg = &dc.col[base.fg];
  2716. }
  2717. if(IS_TRUECOL(base.bg)) {
  2718. colbg.green = TRUEGREEN(base.bg);
  2719. colbg.red = TRUERED(base.bg);
  2720. colbg.blue = TRUEBLUE(base.bg);
  2721. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  2722. bg = &truebg;
  2723. } else {
  2724. bg = &dc.col[base.bg];
  2725. }
  2726. if(base.mode & ATTR_BOLD) {
  2727. if(BETWEEN(base.fg, 0, 7)) {
  2728. /* basic system colors */
  2729. fg = &dc.col[base.fg + 8];
  2730. } else if(BETWEEN(base.fg, 16, 195)) {
  2731. /* 256 colors */
  2732. fg = &dc.col[base.fg + 36];
  2733. } else if(BETWEEN(base.fg, 232, 251)) {
  2734. /* greyscale */
  2735. fg = &dc.col[base.fg + 4];
  2736. }
  2737. /*
  2738. * Those ranges will not be brightened:
  2739. * 8 - 15 bright system colors
  2740. * 196 - 231 highest 256 color cube
  2741. * 252 - 255 brightest colors in greyscale
  2742. */
  2743. font = &dc.bfont;
  2744. frcflags = FRC_BOLD;
  2745. }
  2746. if(IS_SET(MODE_REVERSE)) {
  2747. if(fg == &dc.col[defaultfg]) {
  2748. fg = &dc.col[defaultbg];
  2749. } else {
  2750. colfg.red = ~fg->color.red;
  2751. colfg.green = ~fg->color.green;
  2752. colfg.blue = ~fg->color.blue;
  2753. colfg.alpha = fg->color.alpha;
  2754. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2755. fg = &revfg;
  2756. }
  2757. if(bg == &dc.col[defaultbg]) {
  2758. bg = &dc.col[defaultfg];
  2759. } else {
  2760. colbg.red = ~bg->color.red;
  2761. colbg.green = ~bg->color.green;
  2762. colbg.blue = ~bg->color.blue;
  2763. colbg.alpha = bg->color.alpha;
  2764. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
  2765. bg = &revbg;
  2766. }
  2767. }
  2768. if(base.mode & ATTR_REVERSE) {
  2769. temp = fg;
  2770. fg = bg;
  2771. bg = temp;
  2772. }
  2773. if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
  2774. fg = bg;
  2775. /* Intelligent cleaning up of the borders. */
  2776. if(x == 0) {
  2777. xclear(0, (y == 0)? 0 : winy, borderpx,
  2778. winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
  2779. }
  2780. if(x + charlen >= term.col) {
  2781. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2782. ((y >= term.row-1)? xw.h : (winy + xw.ch)));
  2783. }
  2784. if(y == 0)
  2785. xclear(winx, 0, winx + width, borderpx);
  2786. if(y == term.row-1)
  2787. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2788. /* Clean up the region we want to draw to. */
  2789. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  2790. /* Set the clip region because Xft is sometimes dirty. */
  2791. r.x = 0;
  2792. r.y = 0;
  2793. r.height = xw.ch;
  2794. r.width = width;
  2795. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  2796. for(xp = winx; bytelen > 0;) {
  2797. /*
  2798. * Search for the range in the to be printed string of glyphs
  2799. * that are in the main font. Then print that range. If
  2800. * some glyph is found that is not in the font, do the
  2801. * fallback dance.
  2802. */
  2803. u8fs = s;
  2804. u8fblen = 0;
  2805. u8fl = 0;
  2806. oneatatime = font->width != xw.cw;
  2807. for(;;) {
  2808. u8c = s;
  2809. u8cblen = utf8decode(s, &u8char);
  2810. s += u8cblen;
  2811. bytelen -= u8cblen;
  2812. doesexist = XftCharExists(xw.dpy, font->match, u8char);
  2813. if(oneatatime || !doesexist || bytelen <= 0) {
  2814. if(oneatatime || bytelen <= 0) {
  2815. if(doesexist) {
  2816. u8fl++;
  2817. u8fblen += u8cblen;
  2818. }
  2819. }
  2820. if(u8fl > 0) {
  2821. XftDrawStringUtf8(xw.draw, fg,
  2822. font->match, xp,
  2823. winy + font->ascent,
  2824. (FcChar8 *)u8fs,
  2825. u8fblen);
  2826. xp += xw.cw * u8fl;
  2827. }
  2828. break;
  2829. }
  2830. u8fl++;
  2831. u8fblen += u8cblen;
  2832. }
  2833. if(doesexist) {
  2834. if (oneatatime)
  2835. continue;
  2836. break;
  2837. }
  2838. /* Search the font cache. */
  2839. for(i = 0; i < frclen; i++) {
  2840. if(XftCharExists(xw.dpy, frc[i].font, u8char)
  2841. && frc[i].flags == frcflags) {
  2842. break;
  2843. }
  2844. }
  2845. /* Nothing was found. */
  2846. if(i >= frclen) {
  2847. if(!font->set)
  2848. xloadfontset(font);
  2849. fcsets[0] = font->set;
  2850. /*
  2851. * Nothing was found in the cache. Now use
  2852. * some dozen of Fontconfig calls to get the
  2853. * font for one single character.
  2854. */
  2855. fcpattern = FcPatternDuplicate(font->pattern);
  2856. fccharset = FcCharSetCreate();
  2857. FcCharSetAddChar(fccharset, u8char);
  2858. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  2859. fccharset);
  2860. FcPatternAddBool(fcpattern, FC_SCALABLE,
  2861. FcTrue);
  2862. FcConfigSubstitute(0, fcpattern,
  2863. FcMatchPattern);
  2864. FcDefaultSubstitute(fcpattern);
  2865. fontpattern = FcFontSetMatch(0, fcsets,
  2866. FcTrue, fcpattern, &fcres);
  2867. /*
  2868. * Overwrite or create the new cache entry.
  2869. */
  2870. if(frclen >= LEN(frc)) {
  2871. frclen = LEN(frc) - 1;
  2872. XftFontClose(xw.dpy, frc[frclen].font);
  2873. }
  2874. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  2875. fontpattern);
  2876. frc[frclen].flags = frcflags;
  2877. i = frclen;
  2878. frclen++;
  2879. FcPatternDestroy(fcpattern);
  2880. FcCharSetDestroy(fccharset);
  2881. }
  2882. XftDrawStringUtf8(xw.draw, fg, frc[i].font,
  2883. xp, winy + frc[i].font->ascent,
  2884. (FcChar8 *)u8c, u8cblen);
  2885. xp += xw.cw * wcwidth(u8char);
  2886. }
  2887. /*
  2888. XftDrawStringUtf8(xw.draw, fg, font->set, winx,
  2889. winy + font->ascent, (FcChar8 *)s, bytelen);
  2890. */
  2891. if(base.mode & ATTR_UNDERLINE) {
  2892. XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
  2893. width, 1);
  2894. }
  2895. /* Reset clip to none. */
  2896. XftDrawSetClip(xw.draw, 0);
  2897. }
  2898. void
  2899. xdrawcursor(void) {
  2900. static int oldx = 0, oldy = 0;
  2901. int sl, width, curx;
  2902. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
  2903. LIMIT(oldx, 0, term.col-1);
  2904. LIMIT(oldy, 0, term.row-1);
  2905. curx = term.c.x;
  2906. /* adjust position if in dummy */
  2907. if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
  2908. oldx--;
  2909. if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
  2910. curx--;
  2911. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  2912. /* remove the old cursor */
  2913. sl = utf8size(term.line[oldy][oldx].c);
  2914. width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
  2915. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  2916. oldy, width, sl);
  2917. /* draw the new one */
  2918. if(!(IS_SET(MODE_HIDE))) {
  2919. if(xw.state & WIN_FOCUSED) {
  2920. if(IS_SET(MODE_REVERSE)) {
  2921. g.mode |= ATTR_REVERSE;
  2922. g.fg = defaultcs;
  2923. g.bg = defaultfg;
  2924. }
  2925. sl = utf8size(g.c);
  2926. width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
  2927. ? 2 : 1;
  2928. xdraws(g.c, g, term.c.x, term.c.y, width, sl);
  2929. } else {
  2930. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2931. borderpx + curx * xw.cw,
  2932. borderpx + term.c.y * xw.ch,
  2933. xw.cw - 1, 1);
  2934. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2935. borderpx + curx * xw.cw,
  2936. borderpx + term.c.y * xw.ch,
  2937. 1, xw.ch - 1);
  2938. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2939. borderpx + (curx + 1) * xw.cw - 1,
  2940. borderpx + term.c.y * xw.ch,
  2941. 1, xw.ch - 1);
  2942. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2943. borderpx + curx * xw.cw,
  2944. borderpx + (term.c.y + 1) * xw.ch - 1,
  2945. xw.cw, 1);
  2946. }
  2947. oldx = curx, oldy = term.c.y;
  2948. }
  2949. }
  2950. void
  2951. xsettitle(char *p) {
  2952. XTextProperty prop;
  2953. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  2954. &prop);
  2955. XSetWMName(xw.dpy, xw.win, &prop);
  2956. XFree(prop.value);
  2957. }
  2958. void
  2959. xresettitle(void) {
  2960. xsettitle(opt_title ? opt_title : "st");
  2961. }
  2962. void
  2963. redraw(int timeout) {
  2964. struct timespec tv = {0, timeout * 1000};
  2965. tfulldirt();
  2966. draw();
  2967. if(timeout > 0) {
  2968. nanosleep(&tv, NULL);
  2969. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2970. }
  2971. }
  2972. void
  2973. draw(void) {
  2974. drawregion(0, 0, term.col, term.row);
  2975. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
  2976. xw.h, 0, 0);
  2977. XSetForeground(xw.dpy, dc.gc,
  2978. dc.col[IS_SET(MODE_REVERSE)?
  2979. defaultfg : defaultbg].pixel);
  2980. }
  2981. void
  2982. drawregion(int x1, int y1, int x2, int y2) {
  2983. int ic, ib, x, y, ox, sl;
  2984. Glyph base, new;
  2985. char buf[DRAW_BUF_SIZ];
  2986. bool ena_sel = sel.ob.x != -1;
  2987. long u8char;
  2988. if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
  2989. ena_sel = 0;
  2990. if(!(xw.state & WIN_VISIBLE))
  2991. return;
  2992. for(y = y1; y < y2; y++) {
  2993. if(!term.dirty[y])
  2994. continue;
  2995. xtermclear(0, y, term.col, y);
  2996. term.dirty[y] = 0;
  2997. base = term.line[y][0];
  2998. ic = ib = ox = 0;
  2999. for(x = x1; x < x2; x++) {
  3000. new = term.line[y][x];
  3001. if(new.mode == ATTR_WDUMMY)
  3002. continue;
  3003. if(ena_sel && selected(x, y))
  3004. new.mode ^= ATTR_REVERSE;
  3005. if(ib > 0 && (ATTRCMP(base, new)
  3006. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  3007. xdraws(buf, base, ox, y, ic, ib);
  3008. ic = ib = 0;
  3009. }
  3010. if(ib == 0) {
  3011. ox = x;
  3012. base = new;
  3013. }
  3014. sl = utf8decode(new.c, &u8char);
  3015. memcpy(buf+ib, new.c, sl);
  3016. ib += sl;
  3017. ic += (new.mode & ATTR_WIDE)? 2 : 1;
  3018. }
  3019. if(ib > 0)
  3020. xdraws(buf, base, ox, y, ic, ib);
  3021. }
  3022. xdrawcursor();
  3023. }
  3024. void
  3025. expose(XEvent *ev) {
  3026. XExposeEvent *e = &ev->xexpose;
  3027. if(xw.state & WIN_REDRAW) {
  3028. if(!e->count)
  3029. xw.state &= ~WIN_REDRAW;
  3030. }
  3031. redraw(0);
  3032. }
  3033. void
  3034. visibility(XEvent *ev) {
  3035. XVisibilityEvent *e = &ev->xvisibility;
  3036. if(e->state == VisibilityFullyObscured) {
  3037. xw.state &= ~WIN_VISIBLE;
  3038. } else if(!(xw.state & WIN_VISIBLE)) {
  3039. /* need a full redraw for next Expose, not just a buf copy */
  3040. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  3041. }
  3042. }
  3043. void
  3044. unmap(XEvent *ev) {
  3045. xw.state &= ~WIN_VISIBLE;
  3046. }
  3047. void
  3048. xsetpointermotion(int set) {
  3049. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  3050. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  3051. }
  3052. void
  3053. xseturgency(int add) {
  3054. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  3055. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  3056. XSetWMHints(xw.dpy, xw.win, h);
  3057. XFree(h);
  3058. }
  3059. void
  3060. focus(XEvent *ev) {
  3061. XFocusChangeEvent *e = &ev->xfocus;
  3062. if(e->mode == NotifyGrab)
  3063. return;
  3064. if(ev->type == FocusIn) {
  3065. XSetICFocus(xw.xic);
  3066. xw.state |= WIN_FOCUSED;
  3067. xseturgency(0);
  3068. if(IS_SET(MODE_FOCUS))
  3069. ttywrite("\033[I", 3);
  3070. } else {
  3071. XUnsetICFocus(xw.xic);
  3072. xw.state &= ~WIN_FOCUSED;
  3073. if(IS_SET(MODE_FOCUS))
  3074. ttywrite("\033[O", 3);
  3075. }
  3076. }
  3077. static inline bool
  3078. match(uint mask, uint state) {
  3079. state &= ~ignoremod;
  3080. if(mask == XK_NO_MOD && state)
  3081. return false;
  3082. if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
  3083. return false;
  3084. if(mask == XK_ANY_MOD)
  3085. return true;
  3086. return state == mask;
  3087. }
  3088. void
  3089. numlock(const Arg *dummy) {
  3090. term.numlock ^= 1;
  3091. }
  3092. char*
  3093. kmap(KeySym k, uint state) {
  3094. Key *kp;
  3095. int i;
  3096. /* Check for mapped keys out of X11 function keys. */
  3097. for(i = 0; i < LEN(mappedkeys); i++) {
  3098. if(mappedkeys[i] == k)
  3099. break;
  3100. }
  3101. if(i == LEN(mappedkeys)) {
  3102. if((k & 0xFFFF) < 0xFD00)
  3103. return NULL;
  3104. }
  3105. for(kp = key; kp < key + LEN(key); kp++) {
  3106. if(kp->k != k)
  3107. continue;
  3108. if(!match(kp->mask, state))
  3109. continue;
  3110. if(kp->appkey > 0) {
  3111. if(!IS_SET(MODE_APPKEYPAD))
  3112. continue;
  3113. if(term.numlock && kp->appkey == 2)
  3114. continue;
  3115. } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
  3116. continue;
  3117. }
  3118. if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
  3119. (kp->appcursor > 0
  3120. && !IS_SET(MODE_APPCURSOR))) {
  3121. continue;
  3122. }
  3123. if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
  3124. (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
  3125. continue;
  3126. }
  3127. return kp->s;
  3128. }
  3129. return NULL;
  3130. }
  3131. void
  3132. kpress(XEvent *ev) {
  3133. XKeyEvent *e = &ev->xkey;
  3134. KeySym ksym;
  3135. char xstr[31], buf[32], *customkey, *cp = buf;
  3136. int len, ret;
  3137. long c;
  3138. Status status;
  3139. Shortcut *bp;
  3140. if(IS_SET(MODE_KBDLOCK))
  3141. return;
  3142. len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
  3143. e->state &= ~Mod2Mask;
  3144. /* 1. shortcuts */
  3145. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  3146. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  3147. bp->func(&(bp->arg));
  3148. return;
  3149. }
  3150. }
  3151. /* 2. custom keys from config.h */
  3152. if((customkey = kmap(ksym, e->state))) {
  3153. len = strlen(customkey);
  3154. memcpy(buf, customkey, len);
  3155. /* 3. hardcoded (overrides X lookup) */
  3156. } else {
  3157. if(len == 0)
  3158. return;
  3159. if(len == 1 && e->state & Mod1Mask) {
  3160. if(IS_SET(MODE_8BIT)) {
  3161. if(*xstr < 0177) {
  3162. c = *xstr | 0x80;
  3163. ret = utf8encode(&c, cp);
  3164. cp += ret;
  3165. len = 0;
  3166. }
  3167. } else {
  3168. *cp++ = '\033';
  3169. }
  3170. }
  3171. memcpy(cp, xstr, len);
  3172. len = cp - buf + len;
  3173. }
  3174. ttywrite(buf, len);
  3175. if(IS_SET(MODE_ECHO))
  3176. techo(buf, len);
  3177. }
  3178. void
  3179. cmessage(XEvent *e) {
  3180. /*
  3181. * See xembed specs
  3182. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  3183. */
  3184. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  3185. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  3186. xw.state |= WIN_FOCUSED;
  3187. xseturgency(0);
  3188. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  3189. xw.state &= ~WIN_FOCUSED;
  3190. }
  3191. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  3192. /* Send SIGHUP to shell */
  3193. kill(pid, SIGHUP);
  3194. exit(EXIT_SUCCESS);
  3195. }
  3196. }
  3197. void
  3198. cresize(int width, int height) {
  3199. int col, row;
  3200. if(width != 0)
  3201. xw.w = width;
  3202. if(height != 0)
  3203. xw.h = height;
  3204. col = (xw.w - 2 * borderpx) / xw.cw;
  3205. row = (xw.h - 2 * borderpx) / xw.ch;
  3206. tresize(col, row);
  3207. xresize(col, row);
  3208. ttyresize();
  3209. }
  3210. void
  3211. resize(XEvent *e) {
  3212. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  3213. return;
  3214. cresize(e->xconfigure.width, e->xconfigure.height);
  3215. }
  3216. void
  3217. run(void) {
  3218. XEvent ev;
  3219. int w = xw.w, h = xw.h;
  3220. fd_set rfd;
  3221. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  3222. struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
  3223. /* Waiting for window mapping */
  3224. while(1) {
  3225. XNextEvent(xw.dpy, &ev);
  3226. if(ev.type == ConfigureNotify) {
  3227. w = ev.xconfigure.width;
  3228. h = ev.xconfigure.height;
  3229. } else if(ev.type == MapNotify) {
  3230. break;
  3231. }
  3232. }
  3233. if(!xw.isfixed)
  3234. cresize(w, h);
  3235. else
  3236. cresize(xw.fw, xw.fh);
  3237. ttynew();
  3238. gettimeofday(&lastblink, NULL);
  3239. gettimeofday(&last, NULL);
  3240. for(xev = actionfps;;) {
  3241. FD_ZERO(&rfd);
  3242. FD_SET(cmdfd, &rfd);
  3243. FD_SET(xfd, &rfd);
  3244. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  3245. if(errno == EINTR)
  3246. continue;
  3247. die("select failed: %s\n", SERRNO);
  3248. }
  3249. if(FD_ISSET(cmdfd, &rfd)) {
  3250. ttyread();
  3251. if(blinktimeout) {
  3252. blinkset = tattrset(ATTR_BLINK);
  3253. if(!blinkset)
  3254. MODBIT(term.mode, 0, MODE_BLINK);
  3255. }
  3256. }
  3257. if(FD_ISSET(xfd, &rfd))
  3258. xev = actionfps;
  3259. gettimeofday(&now, NULL);
  3260. drawtimeout.tv_sec = 0;
  3261. drawtimeout.tv_usec = (1000/xfps) * 1000;
  3262. tv = &drawtimeout;
  3263. dodraw = 0;
  3264. if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  3265. tsetdirtattr(ATTR_BLINK);
  3266. term.mode ^= MODE_BLINK;
  3267. gettimeofday(&lastblink, NULL);
  3268. dodraw = 1;
  3269. }
  3270. if(TIMEDIFF(now, last) \
  3271. > (xev? (1000/xfps) : (1000/actionfps))) {
  3272. dodraw = 1;
  3273. last = now;
  3274. }
  3275. if(dodraw) {
  3276. while(XPending(xw.dpy)) {
  3277. XNextEvent(xw.dpy, &ev);
  3278. if(XFilterEvent(&ev, None))
  3279. continue;
  3280. if(handler[ev.type])
  3281. (handler[ev.type])(&ev);
  3282. }
  3283. draw();
  3284. XFlush(xw.dpy);
  3285. if(xev && !FD_ISSET(xfd, &rfd))
  3286. xev--;
  3287. if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  3288. if(blinkset) {
  3289. if(TIMEDIFF(now, lastblink) \
  3290. > blinktimeout) {
  3291. drawtimeout.tv_usec = 1;
  3292. } else {
  3293. drawtimeout.tv_usec = (1000 * \
  3294. (blinktimeout - \
  3295. TIMEDIFF(now,
  3296. lastblink)));
  3297. }
  3298. } else {
  3299. tv = NULL;
  3300. }
  3301. }
  3302. }
  3303. }
  3304. }
  3305. void
  3306. usage(void) {
  3307. die("%s " VERSION " (c) 2010-2013 st engineers\n" \
  3308. "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
  3309. " [-t title] [-w windowid] [-e command ...]\n", argv0);
  3310. }
  3311. int
  3312. main(int argc, char *argv[]) {
  3313. int bitm, xr, yr;
  3314. uint wr, hr;
  3315. char *titles;
  3316. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  3317. xw.isfixed = False;
  3318. ARGBEGIN {
  3319. case 'a':
  3320. allowaltscreen = false;
  3321. break;
  3322. case 'c':
  3323. opt_class = EARGF(usage());
  3324. break;
  3325. case 'e':
  3326. /* eat all remaining arguments */
  3327. if(argc > 1) {
  3328. opt_cmd = &argv[1];
  3329. if(argv[1] != NULL && opt_title == NULL) {
  3330. titles = strdup(argv[1]);
  3331. opt_title = basename(titles);
  3332. }
  3333. }
  3334. goto run;
  3335. case 'f':
  3336. opt_font = EARGF(usage());
  3337. break;
  3338. case 'g':
  3339. bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
  3340. if(bitm & XValue)
  3341. xw.fx = xr;
  3342. if(bitm & YValue)
  3343. xw.fy = yr;
  3344. if(bitm & WidthValue)
  3345. xw.fw = (int)wr;
  3346. if(bitm & HeightValue)
  3347. xw.fh = (int)hr;
  3348. if(bitm & XNegative && xw.fx == 0)
  3349. xw.fx = -1;
  3350. if(bitm & YNegative && xw.fy == 0)
  3351. xw.fy = -1;
  3352. if(xw.fh != 0 && xw.fw != 0)
  3353. xw.isfixed = True;
  3354. break;
  3355. case 'o':
  3356. opt_io = EARGF(usage());
  3357. break;
  3358. case 't':
  3359. opt_title = EARGF(usage());
  3360. break;
  3361. case 'w':
  3362. opt_embed = EARGF(usage());
  3363. break;
  3364. case 'v':
  3365. default:
  3366. usage();
  3367. } ARGEND;
  3368. run:
  3369. setlocale(LC_CTYPE, "");
  3370. XSetLocaleModifiers("");
  3371. tnew(80, 24);
  3372. xinit();
  3373. selinit();
  3374. run();
  3375. return 0;
  3376. }