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.

4066 lines
89 KiB

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