My build of suckless st terminal
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.

4068 lines
89 KiB

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