Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4089 lines
90 KiB

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