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.

2456 lines
55 KiB

12 years ago
13 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
14 years ago
13 years ago
13 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
13 years ago
  1. /* See LICENSE for licence details. */
  2. #define _XOPEN_SOURCE 600
  3. #include <ctype.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <limits.h>
  7. #include <locale.h>
  8. #include <stdarg.h>
  9. #include <stdbool.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <signal.h>
  14. #include <sys/ioctl.h>
  15. #include <sys/select.h>
  16. #include <sys/stat.h>
  17. #include <sys/time.h>
  18. #include <sys/types.h>
  19. #include <sys/wait.h>
  20. #include <time.h>
  21. #include <unistd.h>
  22. #include <X11/Xatom.h>
  23. #include <X11/Xlib.h>
  24. #include <X11/Xutil.h>
  25. #include <X11/cursorfont.h>
  26. #include <X11/keysym.h>
  27. #include <X11/extensions/Xdbe.h>
  28. #if defined(__linux)
  29. #include <pty.h>
  30. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  31. #include <util.h>
  32. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  33. #include <libutil.h>
  34. #endif
  35. #define USAGE \
  36. "st " VERSION " (c) 2010-2012 st engineers\n" \
  37. "usage: st [-t title] [-c class] [-g geometry]" \
  38. " [-w windowid] [-v] [-f file] [-e command...]\n"
  39. /* XEMBED messages */
  40. #define XEMBED_FOCUS_IN 4
  41. #define XEMBED_FOCUS_OUT 5
  42. /* Arbitrary sizes */
  43. #define ESC_BUF_SIZ 256
  44. #define ESC_ARG_SIZ 16
  45. #define STR_BUF_SIZ 256
  46. #define STR_ARG_SIZ 16
  47. #define DRAW_BUF_SIZ 1024
  48. #define UTF_SIZ 4
  49. #define XK_NO_MOD UINT_MAX
  50. #define XK_ANY_MOD 0
  51. #define SELECT_TIMEOUT (20*1000) /* 20 ms */
  52. #define DRAW_TIMEOUT (20*1000) /* 20 ms */
  53. #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
  54. #define SERRNO strerror(errno)
  55. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  56. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  57. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  58. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  59. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  60. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  61. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  62. #define IS_SET(flag) (term.mode & (flag))
  63. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
  64. #define X2COL(x) (((x) - BORDER)/xw.cw)
  65. #define Y2ROW(y) (((y) - BORDER)/xw.ch)
  66. enum glyph_attribute {
  67. ATTR_NULL = 0,
  68. ATTR_REVERSE = 1,
  69. ATTR_UNDERLINE = 2,
  70. ATTR_BOLD = 4,
  71. ATTR_GFX = 8,
  72. ATTR_ITALIC = 16,
  73. ATTR_BLINK = 32,
  74. };
  75. enum cursor_movement {
  76. CURSOR_UP,
  77. CURSOR_DOWN,
  78. CURSOR_LEFT,
  79. CURSOR_RIGHT,
  80. CURSOR_SAVE,
  81. CURSOR_LOAD
  82. };
  83. enum cursor_state {
  84. CURSOR_DEFAULT = 0,
  85. CURSOR_HIDE = 1,
  86. CURSOR_WRAPNEXT = 2
  87. };
  88. enum glyph_state {
  89. GLYPH_SET = 1,
  90. GLYPH_DIRTY = 2
  91. };
  92. enum term_mode {
  93. MODE_WRAP = 1,
  94. MODE_INSERT = 2,
  95. MODE_APPKEYPAD = 4,
  96. MODE_ALTSCREEN = 8,
  97. MODE_CRLF = 16,
  98. MODE_MOUSEBTN = 32,
  99. MODE_MOUSEMOTION = 64,
  100. MODE_MOUSE = 32|64,
  101. MODE_REVERSE = 128
  102. };
  103. enum escape_state {
  104. ESC_START = 1,
  105. ESC_CSI = 2,
  106. ESC_STR = 4, /* DSC, OSC, PM, APC */
  107. ESC_ALTCHARSET = 8,
  108. ESC_STR_END = 16, /* a final string was encountered */
  109. };
  110. enum window_state {
  111. WIN_VISIBLE = 1,
  112. WIN_REDRAW = 2,
  113. WIN_FOCUSED = 4
  114. };
  115. /* bit macro */
  116. #undef B0
  117. enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
  118. typedef unsigned char uchar;
  119. typedef unsigned int uint;
  120. typedef unsigned long ulong;
  121. typedef unsigned short ushort;
  122. typedef struct {
  123. char c[UTF_SIZ]; /* character code */
  124. uchar mode; /* attribute flags */
  125. ushort fg; /* foreground */
  126. ushort bg; /* background */
  127. uchar state; /* state flags */
  128. } Glyph;
  129. typedef Glyph* Line;
  130. typedef struct {
  131. Glyph attr; /* current char attributes */
  132. int x;
  133. int y;
  134. char state;
  135. } TCursor;
  136. /* CSI Escape sequence structs */
  137. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  138. typedef struct {
  139. char buf[ESC_BUF_SIZ]; /* raw string */
  140. int len; /* raw string length */
  141. char priv;
  142. int arg[ESC_ARG_SIZ];
  143. int narg; /* nb of args */
  144. char mode;
  145. } CSIEscape;
  146. /* STR Escape sequence structs */
  147. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  148. typedef struct {
  149. char type; /* ESC type ... */
  150. char buf[STR_BUF_SIZ]; /* raw string */
  151. int len; /* raw string length */
  152. char *args[STR_ARG_SIZ];
  153. int narg; /* nb of args */
  154. } STREscape;
  155. /* Internal representation of the screen */
  156. typedef struct {
  157. int row; /* nb row */
  158. int col; /* nb col */
  159. Line* line; /* screen */
  160. Line* alt; /* alternate screen */
  161. bool* dirty; /* dirtyness of lines */
  162. TCursor c; /* cursor */
  163. int top; /* top scroll limit */
  164. int bot; /* bottom scroll limit */
  165. int mode; /* terminal mode flags */
  166. int esc; /* escape state flags */
  167. bool *tabs;
  168. } Term;
  169. /* Purely graphic info */
  170. typedef struct {
  171. Display* dpy;
  172. Colormap cmap;
  173. Window win;
  174. XdbeBackBuffer buf;
  175. Atom xembed;
  176. XIM xim;
  177. XIC xic;
  178. int scr;
  179. Bool isfixed; /* is fixed geometry? */
  180. int fx, fy, fw, fh; /* fixed geometry */
  181. int w; /* window width */
  182. int h; /* window height */
  183. int ch; /* char height */
  184. int cw; /* char width */
  185. char state; /* focus, redraw, visible */
  186. struct timeval lastdraw;
  187. } XWindow;
  188. typedef struct {
  189. KeySym k;
  190. uint mask;
  191. char s[ESC_BUF_SIZ];
  192. } Key;
  193. /* TODO: use better name for vars... */
  194. typedef struct {
  195. int mode;
  196. int bx, by;
  197. int ex, ey;
  198. struct {int x, y;} b, e;
  199. char *clip;
  200. Atom xtarget;
  201. bool alt;
  202. struct timeval tclick1;
  203. struct timeval tclick2;
  204. } Selection;
  205. #include "config.h"
  206. /* Drawing Context */
  207. typedef struct {
  208. ulong col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
  209. GC gc;
  210. struct {
  211. int ascent;
  212. int descent;
  213. short lbearing;
  214. short rbearing;
  215. XFontSet set;
  216. } font, bfont, ifont, ibfont;
  217. } DC;
  218. static void die(const char*, ...);
  219. static void draw(void);
  220. static void redraw(void);
  221. static void drawregion(int, int, int, int);
  222. static void execsh(void);
  223. static void sigchld(int);
  224. static void run(void);
  225. static bool last_draw_too_old(void);
  226. static void csidump(void);
  227. static void csihandle(void);
  228. static void csiparse(void);
  229. static void csireset(void);
  230. static void strdump(void);
  231. static void strhandle(void);
  232. static void strparse(void);
  233. static void strreset(void);
  234. static void tclearregion(int, int, int, int);
  235. static void tcursor(int);
  236. static void tdeletechar(int);
  237. static void tdeleteline(int);
  238. static void tinsertblank(int);
  239. static void tinsertblankline(int);
  240. static void tmoveto(int, int);
  241. static void tnew(int, int);
  242. static void tnewline(int);
  243. static void tputtab(bool);
  244. static void tputc(char*);
  245. static void treset(void);
  246. static int tresize(int, int);
  247. static void tscrollup(int, int);
  248. static void tscrolldown(int, int);
  249. static void tsetattr(int*, int);
  250. static void tsetchar(char*);
  251. static void tsetscroll(int, int);
  252. static void tswapscreen(void);
  253. static void tsetdirt(int, int);
  254. static void tsetmode(bool, bool, int *, int);
  255. static void tfulldirt(void);
  256. static void ttynew(void);
  257. static void ttyread(void);
  258. static void ttyresize(int, int);
  259. static void ttywrite(const char *, size_t);
  260. static void xdraws(char *, Glyph, int, int, int, int);
  261. static void xhints(void);
  262. static void xclear(int, int, int, int);
  263. static void xcopy(void);
  264. static void xdrawcursor(void);
  265. static void xinit(void);
  266. static void xloadcols(void);
  267. static void xresettitle(void);
  268. static void xseturgency(int);
  269. static void xsetsel(char*);
  270. static void xresize(int, int);
  271. static void expose(XEvent *);
  272. static void visibility(XEvent *);
  273. static void unmap(XEvent *);
  274. static char* kmap(KeySym, uint);
  275. static void kpress(XEvent *);
  276. static void cmessage(XEvent *);
  277. static void resize(XEvent *);
  278. static void focus(XEvent *);
  279. static void brelease(XEvent *);
  280. static void bpress(XEvent *);
  281. static void bmotion(XEvent *);
  282. static void selnotify(XEvent *);
  283. static void selclear(XEvent *);
  284. static void selrequest(XEvent *);
  285. static void selinit(void);
  286. static inline bool selected(int, int);
  287. static void selcopy(void);
  288. static void selpaste(void);
  289. static void selscroll(int, int);
  290. static int utf8decode(char *, long *);
  291. static int utf8encode(long *, char *);
  292. static int utf8size(char *);
  293. static int isfullutf8(char *, int);
  294. static void *xmalloc(size_t);
  295. static void *xrealloc(void *, size_t);
  296. static void (*handler[LASTEvent])(XEvent *) = {
  297. [KeyPress] = kpress,
  298. [ClientMessage] = cmessage,
  299. [ConfigureNotify] = resize,
  300. [VisibilityNotify] = visibility,
  301. [UnmapNotify] = unmap,
  302. [Expose] = expose,
  303. [FocusIn] = focus,
  304. [FocusOut] = focus,
  305. [MotionNotify] = bmotion,
  306. [ButtonPress] = bpress,
  307. [ButtonRelease] = brelease,
  308. [SelectionClear] = selclear,
  309. [SelectionNotify] = selnotify,
  310. [SelectionRequest] = selrequest,
  311. };
  312. /* Globals */
  313. static DC dc;
  314. static XWindow xw;
  315. static Term term;
  316. static CSIEscape csiescseq;
  317. static STREscape strescseq;
  318. static int cmdfd;
  319. static pid_t pid;
  320. static Selection sel;
  321. static int iofd = -1;
  322. static char **opt_cmd = NULL;
  323. static char *opt_io = NULL;
  324. static char *opt_title = NULL;
  325. static char *opt_embed = NULL;
  326. static char *opt_class = NULL;
  327. void *
  328. xmalloc(size_t len) {
  329. void *p = malloc(len);
  330. if(!p)
  331. die("Out of memory");
  332. return p;
  333. }
  334. void *
  335. xrealloc(void *p, size_t len) {
  336. if((p = realloc(p, len)) == NULL)
  337. die("Out of memory");
  338. return p;
  339. }
  340. int
  341. utf8decode(char *s, long *u) {
  342. uchar c;
  343. int i, n, rtn;
  344. rtn = 1;
  345. c = *s;
  346. if(~c & B7) { /* 0xxxxxxx */
  347. *u = c;
  348. return rtn;
  349. } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
  350. *u = c&(B4|B3|B2|B1|B0);
  351. n = 1;
  352. } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
  353. *u = c&(B3|B2|B1|B0);
  354. n = 2;
  355. } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
  356. *u = c & (B2|B1|B0);
  357. n = 3;
  358. } else
  359. goto invalid;
  360. for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
  361. c = *s;
  362. if((c & (B7|B6)) != B7) /* 10xxxxxx */
  363. goto invalid;
  364. *u <<= 6;
  365. *u |= c & (B5|B4|B3|B2|B1|B0);
  366. }
  367. if((n == 1 && *u < 0x80) ||
  368. (n == 2 && *u < 0x800) ||
  369. (n == 3 && *u < 0x10000) ||
  370. (*u >= 0xD800 && *u <= 0xDFFF))
  371. goto invalid;
  372. return rtn;
  373. invalid:
  374. *u = 0xFFFD;
  375. return rtn;
  376. }
  377. int
  378. utf8encode(long *u, char *s) {
  379. uchar *sp;
  380. ulong uc;
  381. int i, n;
  382. sp = (uchar*) s;
  383. uc = *u;
  384. if(uc < 0x80) {
  385. *sp = uc; /* 0xxxxxxx */
  386. return 1;
  387. } else if(*u < 0x800) {
  388. *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
  389. n = 1;
  390. } else if(uc < 0x10000) {
  391. *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
  392. n = 2;
  393. } else if(uc <= 0x10FFFF) {
  394. *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
  395. n = 3;
  396. } else {
  397. goto invalid;
  398. }
  399. for(i=n,++sp; i>0; --i,++sp)
  400. *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
  401. return n+1;
  402. invalid:
  403. /* U+FFFD */
  404. *s++ = '\xEF';
  405. *s++ = '\xBF';
  406. *s = '\xBD';
  407. return 3;
  408. }
  409. /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
  410. UTF-8 otherwise return 0 */
  411. int
  412. isfullutf8(char *s, int b) {
  413. uchar *c1, *c2, *c3;
  414. c1 = (uchar *) s;
  415. c2 = (uchar *) ++s;
  416. c3 = (uchar *) ++s;
  417. if(b < 1)
  418. return 0;
  419. else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
  420. return 0;
  421. else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
  422. ((b == 1) ||
  423. ((b == 2) && (*c2&(B7|B6)) == B7)))
  424. return 0;
  425. else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
  426. ((b == 1) ||
  427. ((b == 2) && (*c2&(B7|B6)) == B7) ||
  428. ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
  429. return 0;
  430. else
  431. return 1;
  432. }
  433. int
  434. utf8size(char *s) {
  435. uchar c = *s;
  436. if(~c&B7)
  437. return 1;
  438. else if((c&(B7|B6|B5)) == (B7|B6))
  439. return 2;
  440. else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
  441. return 3;
  442. else
  443. return 4;
  444. }
  445. void
  446. selinit(void) {
  447. memset(&sel.tclick1, 0, sizeof(sel.tclick1));
  448. memset(&sel.tclick2, 0, sizeof(sel.tclick2));
  449. sel.mode = 0;
  450. sel.bx = -1;
  451. sel.clip = NULL;
  452. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  453. if(sel.xtarget == None)
  454. sel.xtarget = XA_STRING;
  455. }
  456. static inline bool
  457. selected(int x, int y) {
  458. if(sel.ey == y && sel.by == y) {
  459. int bx = MIN(sel.bx, sel.ex);
  460. int ex = MAX(sel.bx, sel.ex);
  461. return BETWEEN(x, bx, ex);
  462. }
  463. return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
  464. || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
  465. }
  466. void
  467. getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
  468. if(b)
  469. *b = e->xbutton.button;
  470. *x = X2COL(e->xbutton.x);
  471. *y = Y2ROW(e->xbutton.y);
  472. sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
  473. sel.b.y = MIN(sel.by, sel.ey);
  474. sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
  475. sel.e.y = MAX(sel.by, sel.ey);
  476. }
  477. void
  478. mousereport(XEvent *e) {
  479. int x = X2COL(e->xbutton.x);
  480. int y = Y2ROW(e->xbutton.y);
  481. int button = e->xbutton.button;
  482. int state = e->xbutton.state;
  483. char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
  484. static int ob, ox, oy;
  485. /* from urxvt */
  486. if(e->xbutton.type == MotionNotify) {
  487. if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
  488. return;
  489. button = ob + 32;
  490. ox = x, oy = y;
  491. } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
  492. button = 3;
  493. } else {
  494. button -= Button1;
  495. if(button >= 3)
  496. button += 64 - 3;
  497. if(e->xbutton.type == ButtonPress) {
  498. ob = button;
  499. ox = x, oy = y;
  500. }
  501. }
  502. buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
  503. + (state & Mod4Mask ? 8 : 0)
  504. + (state & ControlMask ? 16 : 0);
  505. ttywrite(buf, sizeof(buf));
  506. }
  507. void
  508. bpress(XEvent *e) {
  509. if(IS_SET(MODE_MOUSE))
  510. mousereport(e);
  511. else if(e->xbutton.button == Button1) {
  512. if(sel.bx != -1)
  513. tsetdirt(sel.b.y, sel.e.y);
  514. sel.mode = 1;
  515. sel.ex = sel.bx = X2COL(e->xbutton.x);
  516. sel.ey = sel.by = Y2ROW(e->xbutton.y);
  517. }
  518. }
  519. void
  520. selcopy(void) {
  521. char *str, *ptr;
  522. int x, y, bufsize, is_selected = 0;
  523. if(sel.bx == -1)
  524. str = NULL;
  525. else {
  526. bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
  527. ptr = str = xmalloc(bufsize);
  528. /* append every set & selected glyph to the selection */
  529. for(y = 0; y < term.row; y++) {
  530. for(x = 0; x < term.col; x++) {
  531. is_selected = selected(x, y);
  532. if((term.line[y][x].state & GLYPH_SET) && is_selected) {
  533. int size = utf8size(term.line[y][x].c);
  534. memcpy(ptr, term.line[y][x].c, size);
  535. ptr += size;
  536. }
  537. }
  538. /* \n at the end of every selected line except for the last one */
  539. if(is_selected && y < sel.e.y)
  540. *ptr++ = '\n';
  541. }
  542. *ptr = 0;
  543. }
  544. sel.alt = IS_SET(MODE_ALTSCREEN);
  545. xsetsel(str);
  546. }
  547. void
  548. selnotify(XEvent *e) {
  549. ulong nitems, ofs, rem;
  550. int format;
  551. uchar *data;
  552. Atom type;
  553. ofs = 0;
  554. do {
  555. if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
  556. False, AnyPropertyType, &type, &format,
  557. &nitems, &rem, &data)) {
  558. fprintf(stderr, "Clipboard allocation failed\n");
  559. return;
  560. }
  561. ttywrite((const char *) data, nitems * format / 8);
  562. XFree(data);
  563. /* number of 32-bit chunks returned */
  564. ofs += nitems * format / 32;
  565. } while(rem > 0);
  566. }
  567. void
  568. selpaste() {
  569. XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
  570. }
  571. void selclear(XEvent *e) {
  572. if(sel.bx == -1)
  573. return;
  574. sel.bx = -1;
  575. tsetdirt(sel.b.y, sel.e.y);
  576. draw();
  577. }
  578. void
  579. selrequest(XEvent *e) {
  580. XSelectionRequestEvent *xsre;
  581. XSelectionEvent xev;
  582. Atom xa_targets;
  583. xsre = (XSelectionRequestEvent *) e;
  584. xev.type = SelectionNotify;
  585. xev.requestor = xsre->requestor;
  586. xev.selection = xsre->selection;
  587. xev.target = xsre->target;
  588. xev.time = xsre->time;
  589. /* reject */
  590. xev.property = None;
  591. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  592. if(xsre->target == xa_targets) {
  593. /* respond with the supported type */
  594. Atom string = sel.xtarget;
  595. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  596. XA_ATOM, 32, PropModeReplace,
  597. (uchar *) &string, 1);
  598. xev.property = xsre->property;
  599. } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
  600. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  601. xsre->target, 8, PropModeReplace,
  602. (uchar *) sel.clip, strlen(sel.clip));
  603. xev.property = xsre->property;
  604. }
  605. /* all done, send a notification to the listener */
  606. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  607. fprintf(stderr, "Error sending SelectionNotify event\n");
  608. }
  609. void
  610. xsetsel(char *str) {
  611. /* register the selection for both the clipboard and the primary */
  612. Atom clipboard;
  613. free(sel.clip);
  614. sel.clip = str;
  615. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
  616. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  617. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  618. XFlush(xw.dpy);
  619. }
  620. void
  621. brelease(XEvent *e) {
  622. if(IS_SET(MODE_MOUSE)) {
  623. mousereport(e);
  624. return;
  625. }
  626. if(e->xbutton.button == Button2)
  627. selpaste();
  628. else if(e->xbutton.button == Button1) {
  629. sel.mode = 0;
  630. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  631. term.dirty[sel.ey] = 1;
  632. if(sel.bx == sel.ex && sel.by == sel.ey) {
  633. struct timeval now;
  634. sel.bx = -1;
  635. gettimeofday(&now, NULL);
  636. if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
  637. /* triple click on the line */
  638. sel.b.x = sel.bx = 0;
  639. sel.e.x = sel.ex = term.col;
  640. sel.b.y = sel.e.y = sel.ey;
  641. selcopy();
  642. } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
  643. /* double click to select word */
  644. sel.bx = sel.ex;
  645. while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
  646. term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
  647. sel.b.x = sel.bx;
  648. while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
  649. term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
  650. sel.e.x = sel.ex;
  651. sel.b.y = sel.e.y = sel.ey;
  652. selcopy();
  653. }
  654. } else
  655. selcopy();
  656. }
  657. memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
  658. gettimeofday(&sel.tclick1, NULL);
  659. draw();
  660. }
  661. void
  662. bmotion(XEvent *e) {
  663. if(IS_SET(MODE_MOUSE)) {
  664. mousereport(e);
  665. return;
  666. }
  667. if(sel.mode) {
  668. int oldey = sel.ey, oldex = sel.ex;
  669. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  670. if(oldey != sel.ey || oldex != sel.ex) {
  671. int starty = MIN(oldey, sel.ey);
  672. int endy = MAX(oldey, sel.ey);
  673. tsetdirt(starty, endy);
  674. draw();
  675. }
  676. }
  677. }
  678. void
  679. die(const char *errstr, ...) {
  680. va_list ap;
  681. va_start(ap, errstr);
  682. vfprintf(stderr, errstr, ap);
  683. va_end(ap);
  684. exit(EXIT_FAILURE);
  685. }
  686. void
  687. execsh(void) {
  688. char **args;
  689. char *envshell = getenv("SHELL");
  690. unsetenv("COLUMNS");
  691. unsetenv("LINES");
  692. unsetenv("TERMCAP");
  693. signal(SIGCHLD, SIG_DFL);
  694. signal(SIGHUP, SIG_DFL);
  695. signal(SIGINT, SIG_DFL);
  696. signal(SIGQUIT, SIG_DFL);
  697. signal(SIGTERM, SIG_DFL);
  698. signal(SIGALRM, SIG_DFL);
  699. DEFAULT(envshell, SHELL);
  700. putenv("TERM="TNAME);
  701. args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
  702. execvp(args[0], args);
  703. exit(EXIT_FAILURE);
  704. }
  705. void
  706. sigchld(int a) {
  707. int stat = 0;
  708. if(waitpid(pid, &stat, 0) < 0)
  709. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  710. if(WIFEXITED(stat))
  711. exit(WEXITSTATUS(stat));
  712. else
  713. exit(EXIT_FAILURE);
  714. }
  715. void
  716. ttynew(void) {
  717. int m, s;
  718. /* seems to work fine on linux, openbsd and freebsd */
  719. struct winsize w = {term.row, term.col, 0, 0};
  720. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  721. die("openpty failed: %s\n", SERRNO);
  722. switch(pid = fork()) {
  723. case -1:
  724. die("fork failed\n");
  725. break;
  726. case 0:
  727. setsid(); /* create a new process group */
  728. dup2(s, STDIN_FILENO);
  729. dup2(s, STDOUT_FILENO);
  730. dup2(s, STDERR_FILENO);
  731. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  732. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  733. close(s);
  734. close(m);
  735. execsh();
  736. break;
  737. default:
  738. close(s);
  739. cmdfd = m;
  740. signal(SIGCHLD, sigchld);
  741. if(opt_io) {
  742. if(!strcmp(opt_io, "-")) {
  743. iofd = STDOUT_FILENO;
  744. } else {
  745. if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
  746. fprintf(stderr, "Error opening %s:%s\n",
  747. opt_io, strerror(errno));
  748. }
  749. }
  750. }
  751. }
  752. }
  753. void
  754. dump(char c) {
  755. static int col;
  756. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  757. if(++col % 10 == 0)
  758. fprintf(stderr, "\n");
  759. }
  760. void
  761. ttyread(void) {
  762. static char buf[BUFSIZ];
  763. static int buflen = 0;
  764. char *ptr;
  765. char s[UTF_SIZ];
  766. int charsize; /* size of utf8 char in bytes */
  767. long utf8c;
  768. int ret;
  769. /* append read bytes to unprocessed bytes */
  770. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  771. die("Couldn't read from shell: %s\n", SERRNO);
  772. /* process every complete utf8 char */
  773. buflen += ret;
  774. ptr = buf;
  775. while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
  776. charsize = utf8decode(ptr, &utf8c);
  777. utf8encode(&utf8c, s);
  778. tputc(s);
  779. ptr += charsize;
  780. buflen -= charsize;
  781. }
  782. /* keep any uncomplete utf8 char for the next call */
  783. memmove(buf, ptr, buflen);
  784. }
  785. void
  786. ttywrite(const char *s, size_t n) {
  787. if(write(cmdfd, s, n) == -1)
  788. die("write error on tty: %s\n", SERRNO);
  789. }
  790. void
  791. ttyresize(int x, int y) {
  792. struct winsize w;
  793. w.ws_row = term.row;
  794. w.ws_col = term.col;
  795. w.ws_xpixel = xw.w;
  796. w.ws_ypixel = xw.h;
  797. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  798. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  799. }
  800. void
  801. tsetdirt(int top, int bot)
  802. {
  803. int i;
  804. LIMIT(top, 0, term.row-1);
  805. LIMIT(bot, 0, term.row-1);
  806. for(i = top; i <= bot; i++)
  807. term.dirty[i] = 1;
  808. }
  809. void
  810. tfulldirt(void)
  811. {
  812. tsetdirt(0, term.row-1);
  813. }
  814. void
  815. tcursor(int mode) {
  816. static TCursor c;
  817. if(mode == CURSOR_SAVE)
  818. c = term.c;
  819. else if(mode == CURSOR_LOAD)
  820. term.c = c, tmoveto(c.x, c.y);
  821. }
  822. void
  823. treset(void) {
  824. unsigned i;
  825. term.c = (TCursor){{
  826. .mode = ATTR_NULL,
  827. .fg = DefaultFG,
  828. .bg = DefaultBG
  829. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  830. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  831. for(i = TAB; i < term.col; i += TAB)
  832. term.tabs[i] = 1;
  833. term.top = 0, term.bot = term.row - 1;
  834. term.mode = MODE_WRAP;
  835. tclearregion(0, 0, term.col-1, term.row-1);
  836. }
  837. void
  838. tnew(int col, int row) {
  839. /* set screen size */
  840. term.row = row, term.col = col;
  841. term.line = xmalloc(term.row * sizeof(Line));
  842. term.alt = xmalloc(term.row * sizeof(Line));
  843. term.dirty = xmalloc(term.row * sizeof(*term.dirty));
  844. term.tabs = xmalloc(term.col * sizeof(*term.tabs));
  845. for(row = 0; row < term.row; row++) {
  846. term.line[row] = xmalloc(term.col * sizeof(Glyph));
  847. term.alt [row] = xmalloc(term.col * sizeof(Glyph));
  848. term.dirty[row] = 0;
  849. }
  850. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  851. /* setup screen */
  852. treset();
  853. }
  854. void
  855. tswapscreen(void) {
  856. Line* tmp = term.line;
  857. term.line = term.alt;
  858. term.alt = tmp;
  859. term.mode ^= MODE_ALTSCREEN;
  860. tfulldirt();
  861. }
  862. void
  863. tscrolldown(int orig, int n) {
  864. int i;
  865. Line temp;
  866. LIMIT(n, 0, term.bot-orig+1);
  867. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  868. for(i = term.bot; i >= orig+n; i--) {
  869. temp = term.line[i];
  870. term.line[i] = term.line[i-n];
  871. term.line[i-n] = temp;
  872. term.dirty[i] = 1;
  873. term.dirty[i-n] = 1;
  874. }
  875. selscroll(orig, n);
  876. }
  877. void
  878. tscrollup(int orig, int n) {
  879. int i;
  880. Line temp;
  881. LIMIT(n, 0, term.bot-orig+1);
  882. tclearregion(0, orig, term.col-1, orig+n-1);
  883. for(i = orig; i <= term.bot-n; i++) {
  884. temp = term.line[i];
  885. term.line[i] = term.line[i+n];
  886. term.line[i+n] = temp;
  887. term.dirty[i] = 1;
  888. term.dirty[i+n] = 1;
  889. }
  890. selscroll(orig, -n);
  891. }
  892. void
  893. selscroll(int orig, int n) {
  894. if(sel.bx == -1)
  895. return;
  896. if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
  897. if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
  898. sel.bx = -1;
  899. return;
  900. }
  901. if(sel.by < term.top) {
  902. sel.by = term.top;
  903. sel.bx = 0;
  904. }
  905. if(sel.ey > term.bot) {
  906. sel.ey = term.bot;
  907. sel.ex = term.col;
  908. }
  909. sel.b.y = sel.by, sel.b.x = sel.bx;
  910. sel.e.y = sel.ey, sel.e.x = sel.ex;
  911. }
  912. }
  913. void
  914. tnewline(int first_col) {
  915. int y = term.c.y;
  916. if(y == term.bot)
  917. tscrollup(term.top, 1);
  918. else
  919. y++;
  920. tmoveto(first_col ? 0 : term.c.x, y);
  921. }
  922. void
  923. csiparse(void) {
  924. /* int noarg = 1; */
  925. char *p = csiescseq.buf;
  926. csiescseq.narg = 0;
  927. if(*p == '?')
  928. csiescseq.priv = 1, p++;
  929. while(p < csiescseq.buf+csiescseq.len) {
  930. while(isdigit(*p)) {
  931. csiescseq.arg[csiescseq.narg] *= 10;
  932. csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
  933. }
  934. if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
  935. csiescseq.narg++, p++;
  936. else {
  937. csiescseq.mode = *p;
  938. csiescseq.narg++;
  939. return;
  940. }
  941. }
  942. }
  943. void
  944. tmoveto(int x, int y) {
  945. LIMIT(x, 0, term.col-1);
  946. LIMIT(y, 0, term.row-1);
  947. term.c.state &= ~CURSOR_WRAPNEXT;
  948. term.c.x = x;
  949. term.c.y = y;
  950. }
  951. void
  952. tsetchar(char *c) {
  953. term.dirty[term.c.y] = 1;
  954. term.line[term.c.y][term.c.x] = term.c.attr;
  955. memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
  956. term.line[term.c.y][term.c.x].state |= GLYPH_SET;
  957. }
  958. void
  959. tclearregion(int x1, int y1, int x2, int y2) {
  960. int x, y, temp;
  961. if(x1 > x2)
  962. temp = x1, x1 = x2, x2 = temp;
  963. if(y1 > y2)
  964. temp = y1, y1 = y2, y2 = temp;
  965. LIMIT(x1, 0, term.col-1);
  966. LIMIT(x2, 0, term.col-1);
  967. LIMIT(y1, 0, term.row-1);
  968. LIMIT(y2, 0, term.row-1);
  969. for(y = y1; y <= y2; y++) {
  970. term.dirty[y] = 1;
  971. for(x = x1; x <= x2; x++)
  972. term.line[y][x].state = 0;
  973. }
  974. }
  975. void
  976. tdeletechar(int n) {
  977. int src = term.c.x + n;
  978. int dst = term.c.x;
  979. int size = term.col - src;
  980. term.dirty[term.c.y] = 1;
  981. if(src >= term.col) {
  982. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  983. return;
  984. }
  985. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  986. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  987. }
  988. void
  989. tinsertblank(int n) {
  990. int src = term.c.x;
  991. int dst = src + n;
  992. int size = term.col - dst;
  993. term.dirty[term.c.y] = 1;
  994. if(dst >= term.col) {
  995. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  996. return;
  997. }
  998. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  999. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1000. }
  1001. void
  1002. tinsertblankline(int n) {
  1003. if(term.c.y < term.top || term.c.y > term.bot)
  1004. return;
  1005. tscrolldown(term.c.y, n);
  1006. }
  1007. void
  1008. tdeleteline(int n) {
  1009. if(term.c.y < term.top || term.c.y > term.bot)
  1010. return;
  1011. tscrollup(term.c.y, n);
  1012. }
  1013. void
  1014. tsetattr(int *attr, int l) {
  1015. int i;
  1016. for(i = 0; i < l; i++) {
  1017. switch(attr[i]) {
  1018. case 0:
  1019. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
  1020. | ATTR_ITALIC | ATTR_BLINK);
  1021. term.c.attr.fg = DefaultFG;
  1022. term.c.attr.bg = DefaultBG;
  1023. break;
  1024. case 1:
  1025. term.c.attr.mode |= ATTR_BOLD;
  1026. break;
  1027. case 3: /* enter standout (highlight) */
  1028. term.c.attr.mode |= ATTR_ITALIC;
  1029. break;
  1030. case 4:
  1031. term.c.attr.mode |= ATTR_UNDERLINE;
  1032. break;
  1033. case 5:
  1034. term.c.attr.mode |= ATTR_BLINK;
  1035. break;
  1036. case 7:
  1037. term.c.attr.mode |= ATTR_REVERSE;
  1038. break;
  1039. case 21:
  1040. case 22:
  1041. term.c.attr.mode &= ~ATTR_BOLD;
  1042. break;
  1043. case 23: /* leave standout (highlight) mode */
  1044. term.c.attr.mode &= ~ATTR_ITALIC;
  1045. break;
  1046. case 24:
  1047. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1048. break;
  1049. case 25:
  1050. term.c.attr.mode &= ~ATTR_BLINK;
  1051. break;
  1052. case 27:
  1053. term.c.attr.mode &= ~ATTR_REVERSE;
  1054. break;
  1055. case 38:
  1056. if(i + 2 < l && attr[i + 1] == 5) {
  1057. i += 2;
  1058. if(BETWEEN(attr[i], 0, 255))
  1059. term.c.attr.fg = attr[i];
  1060. else
  1061. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
  1062. }
  1063. else
  1064. fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
  1065. break;
  1066. case 39:
  1067. term.c.attr.fg = DefaultFG;
  1068. break;
  1069. case 48:
  1070. if(i + 2 < l && attr[i + 1] == 5) {
  1071. i += 2;
  1072. if(BETWEEN(attr[i], 0, 255))
  1073. term.c.attr.bg = attr[i];
  1074. else
  1075. fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
  1076. }
  1077. else
  1078. fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
  1079. break;
  1080. case 49:
  1081. term.c.attr.bg = DefaultBG;
  1082. break;
  1083. default:
  1084. if(BETWEEN(attr[i], 30, 37))
  1085. term.c.attr.fg = attr[i] - 30;
  1086. else if(BETWEEN(attr[i], 40, 47))
  1087. term.c.attr.bg = attr[i] - 40;
  1088. else if(BETWEEN(attr[i], 90, 97))
  1089. term.c.attr.fg = attr[i] - 90 + 8;
  1090. else if(BETWEEN(attr[i], 100, 107))
  1091. term.c.attr.bg = attr[i] - 100 + 8;
  1092. else
  1093. fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
  1094. break;
  1095. }
  1096. }
  1097. }
  1098. void
  1099. tsetscroll(int t, int b) {
  1100. int temp;
  1101. LIMIT(t, 0, term.row-1);
  1102. LIMIT(b, 0, term.row-1);
  1103. if(t > b) {
  1104. temp = t;
  1105. t = b;
  1106. b = temp;
  1107. }
  1108. term.top = t;
  1109. term.bot = b;
  1110. }
  1111. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1112. void
  1113. tsetmode(bool priv, bool set, int *args, int narg) {
  1114. int *lim, mode;
  1115. for(lim = args + narg; args < lim; ++args) {
  1116. if(priv) {
  1117. switch(*args) {
  1118. case 1:
  1119. MODBIT(term.mode, set, MODE_APPKEYPAD);
  1120. break;
  1121. case 5: /* DECSCNM -- Reverve video */
  1122. mode = term.mode;
  1123. MODBIT(term.mode,set, MODE_REVERSE);
  1124. if(mode != term.mode)
  1125. redraw();
  1126. break;
  1127. case 7:
  1128. MODBIT(term.mode, set, MODE_WRAP);
  1129. break;
  1130. case 20:
  1131. MODBIT(term.mode, set, MODE_CRLF);
  1132. break;
  1133. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1134. break;
  1135. case 25:
  1136. MODBIT(term.c.state, !set, CURSOR_HIDE);
  1137. break;
  1138. case 1000: /* 1000,1002: enable xterm mouse report */
  1139. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1140. break;
  1141. case 1002:
  1142. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1143. break;
  1144. case 1049: /* = 1047 and 1048 */
  1145. case 47:
  1146. case 1047:
  1147. if(IS_SET(MODE_ALTSCREEN))
  1148. tclearregion(0, 0, term.col-1, term.row-1);
  1149. if((set && !IS_SET(MODE_ALTSCREEN)) ||
  1150. (!set && IS_SET(MODE_ALTSCREEN))) {
  1151. tswapscreen();
  1152. }
  1153. if(*args != 1049)
  1154. break;
  1155. /* pass through */
  1156. case 1048:
  1157. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1158. break;
  1159. default:
  1160. fprintf(stderr,
  1161. "erresc: unknown private set/reset mode %d\n",
  1162. *args);
  1163. break;
  1164. }
  1165. } else {
  1166. switch(*args) {
  1167. case 4:
  1168. MODBIT(term.mode, set, MODE_INSERT);
  1169. break;
  1170. default:
  1171. fprintf(stderr,
  1172. "erresc: unknown set/reset mode %d\n",
  1173. *args);
  1174. break;
  1175. }
  1176. }
  1177. }
  1178. }
  1179. #undef MODBIT
  1180. void
  1181. csihandle(void) {
  1182. switch(csiescseq.mode) {
  1183. default:
  1184. unknown:
  1185. fprintf(stderr, "erresc: unknown csi ");
  1186. csidump();
  1187. /* die(""); */
  1188. break;
  1189. case '@': /* ICH -- Insert <n> blank char */
  1190. DEFAULT(csiescseq.arg[0], 1);
  1191. tinsertblank(csiescseq.arg[0]);
  1192. break;
  1193. case 'A': /* CUU -- Cursor <n> Up */
  1194. case 'e':
  1195. DEFAULT(csiescseq.arg[0], 1);
  1196. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1197. break;
  1198. case 'B': /* CUD -- Cursor <n> Down */
  1199. DEFAULT(csiescseq.arg[0], 1);
  1200. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1201. break;
  1202. case 'C': /* CUF -- Cursor <n> Forward */
  1203. case 'a':
  1204. DEFAULT(csiescseq.arg[0], 1);
  1205. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1206. break;
  1207. case 'D': /* CUB -- Cursor <n> Backward */
  1208. DEFAULT(csiescseq.arg[0], 1);
  1209. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1210. break;
  1211. case 'E': /* CNL -- Cursor <n> Down and first col */
  1212. DEFAULT(csiescseq.arg[0], 1);
  1213. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1214. break;
  1215. case 'F': /* CPL -- Cursor <n> Up and first col */
  1216. DEFAULT(csiescseq.arg[0], 1);
  1217. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1218. break;
  1219. case 'g': /* TBC -- Tabulation clear */
  1220. switch (csiescseq.arg[0]) {
  1221. case 0: /* clear current tab stop */
  1222. term.tabs[term.c.x] = 0;
  1223. break;
  1224. case 3: /* clear all the tabs */
  1225. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1226. break;
  1227. default:
  1228. goto unknown;
  1229. }
  1230. break;
  1231. case 'G': /* CHA -- Move to <col> */
  1232. case '`': /* HPA */
  1233. DEFAULT(csiescseq.arg[0], 1);
  1234. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1235. break;
  1236. case 'H': /* CUP -- Move to <row> <col> */
  1237. case 'f': /* HVP */
  1238. DEFAULT(csiescseq.arg[0], 1);
  1239. DEFAULT(csiescseq.arg[1], 1);
  1240. tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1241. break;
  1242. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1243. DEFAULT(csiescseq.arg[0], 1);
  1244. while(csiescseq.arg[0]--)
  1245. tputtab(1);
  1246. break;
  1247. case 'J': /* ED -- Clear screen */
  1248. sel.bx = -1;
  1249. switch(csiescseq.arg[0]) {
  1250. case 0: /* below */
  1251. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1252. if(term.c.y < term.row-1)
  1253. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  1254. break;
  1255. case 1: /* above */
  1256. if(term.c.y > 1)
  1257. tclearregion(0, 0, term.col-1, term.c.y-1);
  1258. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1259. break;
  1260. case 2: /* all */
  1261. tclearregion(0, 0, term.col-1, term.row-1);
  1262. break;
  1263. default:
  1264. goto unknown;
  1265. }
  1266. break;
  1267. case 'K': /* EL -- Clear line */
  1268. switch(csiescseq.arg[0]) {
  1269. case 0: /* right */
  1270. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1271. break;
  1272. case 1: /* left */
  1273. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1274. break;
  1275. case 2: /* all */
  1276. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1277. break;
  1278. }
  1279. break;
  1280. case 'S': /* SU -- Scroll <n> line up */
  1281. DEFAULT(csiescseq.arg[0], 1);
  1282. tscrollup(term.top, csiescseq.arg[0]);
  1283. break;
  1284. case 'T': /* SD -- Scroll <n> line down */
  1285. DEFAULT(csiescseq.arg[0], 1);
  1286. tscrolldown(term.top, csiescseq.arg[0]);
  1287. break;
  1288. case 'L': /* IL -- Insert <n> blank lines */
  1289. DEFAULT(csiescseq.arg[0], 1);
  1290. tinsertblankline(csiescseq.arg[0]);
  1291. break;
  1292. case 'l': /* RM -- Reset Mode */
  1293. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1294. break;
  1295. case 'M': /* DL -- Delete <n> lines */
  1296. DEFAULT(csiescseq.arg[0], 1);
  1297. tdeleteline(csiescseq.arg[0]);
  1298. break;
  1299. case 'X': /* ECH -- Erase <n> char */
  1300. DEFAULT(csiescseq.arg[0], 1);
  1301. tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
  1302. break;
  1303. case 'P': /* DCH -- Delete <n> char */
  1304. DEFAULT(csiescseq.arg[0], 1);
  1305. tdeletechar(csiescseq.arg[0]);
  1306. break;
  1307. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1308. DEFAULT(csiescseq.arg[0], 1);
  1309. while(csiescseq.arg[0]--)
  1310. tputtab(0);
  1311. break;
  1312. case 'd': /* VPA -- Move to <row> */
  1313. DEFAULT(csiescseq.arg[0], 1);
  1314. tmoveto(term.c.x, csiescseq.arg[0]-1);
  1315. break;
  1316. case 'h': /* SM -- Set terminal mode */
  1317. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1318. break;
  1319. case 'm': /* SGR -- Terminal attribute (color) */
  1320. tsetattr(csiescseq.arg, csiescseq.narg);
  1321. break;
  1322. case 'r': /* DECSTBM -- Set Scrolling Region */
  1323. if(csiescseq.priv)
  1324. goto unknown;
  1325. else {
  1326. DEFAULT(csiescseq.arg[0], 1);
  1327. DEFAULT(csiescseq.arg[1], term.row);
  1328. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1329. tmoveto(0, 0);
  1330. }
  1331. break;
  1332. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1333. tcursor(CURSOR_SAVE);
  1334. break;
  1335. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1336. tcursor(CURSOR_LOAD);
  1337. break;
  1338. }
  1339. }
  1340. void
  1341. csidump(void) {
  1342. int i;
  1343. printf("ESC[");
  1344. for(i = 0; i < csiescseq.len; i++) {
  1345. uint c = csiescseq.buf[i] & 0xff;
  1346. if(isprint(c)) putchar(c);
  1347. else if(c == '\n') printf("(\\n)");
  1348. else if(c == '\r') printf("(\\r)");
  1349. else if(c == 0x1b) printf("(\\e)");
  1350. else printf("(%02x)", c);
  1351. }
  1352. putchar('\n');
  1353. }
  1354. void
  1355. csireset(void) {
  1356. memset(&csiescseq, 0, sizeof(csiescseq));
  1357. }
  1358. void
  1359. strhandle(void) {
  1360. char *p;
  1361. /*
  1362. * TODO: make this being useful in case of color palette change.
  1363. */
  1364. strparse();
  1365. p = strescseq.buf;
  1366. switch(strescseq.type) {
  1367. case ']': /* OSC -- Operating System Command */
  1368. switch(p[0]) {
  1369. case '0':
  1370. case '1':
  1371. case '2':
  1372. /*
  1373. * TODO: Handle special chars in string, like umlauts.
  1374. */
  1375. if(p[1] == ';') {
  1376. XStoreName(xw.dpy, xw.win, strescseq.buf+2);
  1377. }
  1378. break;
  1379. case ';':
  1380. XStoreName(xw.dpy, xw.win, strescseq.buf+1);
  1381. break;
  1382. case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
  1383. break;
  1384. default:
  1385. fprintf(stderr, "erresc: unknown str ");
  1386. strdump();
  1387. break;
  1388. }
  1389. break;
  1390. case 'k': /* old title set compatibility */
  1391. XStoreName(xw.dpy, xw.win, strescseq.buf);
  1392. break;
  1393. case 'P': /* DSC -- Device Control String */
  1394. case '_': /* APC -- Application Program Command */
  1395. case '^': /* PM -- Privacy Message */
  1396. default:
  1397. fprintf(stderr, "erresc: unknown str ");
  1398. strdump();
  1399. /* die(""); */
  1400. break;
  1401. }
  1402. }
  1403. void
  1404. strparse(void) {
  1405. /*
  1406. * TODO: Implement parsing like for CSI when required.
  1407. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1408. */
  1409. return;
  1410. }
  1411. void
  1412. strdump(void) {
  1413. int i;
  1414. printf("ESC%c", strescseq.type);
  1415. for(i = 0; i < strescseq.len; i++) {
  1416. uint c = strescseq.buf[i] & 0xff;
  1417. if(isprint(c)) putchar(c);
  1418. else if(c == '\n') printf("(\\n)");
  1419. else if(c == '\r') printf("(\\r)");
  1420. else if(c == 0x1b) printf("(\\e)");
  1421. else printf("(%02x)", c);
  1422. }
  1423. printf("ESC\\\n");
  1424. }
  1425. void
  1426. strreset(void) {
  1427. memset(&strescseq, 0, sizeof(strescseq));
  1428. }
  1429. void
  1430. tputtab(bool forward) {
  1431. unsigned x = term.c.x;
  1432. if(forward) {
  1433. if(x == term.col)
  1434. return;
  1435. for(++x; x < term.col && !term.tabs[x]; ++x)
  1436. /* nothing */ ;
  1437. } else {
  1438. if(x == 0)
  1439. return;
  1440. for(--x; x > 0 && !term.tabs[x]; --x)
  1441. /* nothing */ ;
  1442. }
  1443. tmoveto(x, term.c.y);
  1444. }
  1445. void
  1446. tputc(char *c) {
  1447. char ascii = *c;
  1448. if(iofd != -1)
  1449. write(iofd, c, 1);
  1450. if(term.esc & ESC_START) {
  1451. if(term.esc & ESC_CSI) {
  1452. csiescseq.buf[csiescseq.len++] = ascii;
  1453. if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
  1454. term.esc = 0;
  1455. csiparse(), csihandle();
  1456. }
  1457. } else if(term.esc & ESC_STR) {
  1458. switch(ascii) {
  1459. case '\033':
  1460. term.esc = ESC_START | ESC_STR_END;
  1461. break;
  1462. case '\a': /* backwards compatibility to xterm */
  1463. term.esc = 0;
  1464. strhandle();
  1465. break;
  1466. default:
  1467. strescseq.buf[strescseq.len++] = ascii;
  1468. if(strescseq.len+1 >= STR_BUF_SIZ) {
  1469. term.esc = 0;
  1470. strhandle();
  1471. }
  1472. }
  1473. } else if(term.esc & ESC_STR_END) {
  1474. term.esc = 0;
  1475. if(ascii == '\\')
  1476. strhandle();
  1477. } else if(term.esc & ESC_ALTCHARSET) {
  1478. switch(ascii) {
  1479. case '0': /* Line drawing crap */
  1480. term.c.attr.mode |= ATTR_GFX;
  1481. break;
  1482. case 'B': /* Back to regular text */
  1483. term.c.attr.mode &= ~ATTR_GFX;
  1484. break;
  1485. default:
  1486. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1487. }
  1488. term.esc = 0;
  1489. } else {
  1490. switch(ascii) {
  1491. case '[':
  1492. term.esc |= ESC_CSI;
  1493. break;
  1494. case 'P': /* DCS -- Device Control String */
  1495. case '_': /* APC -- Application Program Command */
  1496. case '^': /* PM -- Privacy Message */
  1497. case ']': /* OSC -- Operating System Command */
  1498. case 'k': /* old title set compatibility */
  1499. strreset();
  1500. strescseq.type = ascii;
  1501. term.esc |= ESC_STR;
  1502. break;
  1503. case '(':
  1504. term.esc |= ESC_ALTCHARSET;
  1505. break;
  1506. case 'D': /* IND -- Linefeed */
  1507. if(term.c.y == term.bot)
  1508. tscrollup(term.top, 1);
  1509. else
  1510. tmoveto(term.c.x, term.c.y+1);
  1511. term.esc = 0;
  1512. break;
  1513. case 'E': /* NEL -- Next line */
  1514. tnewline(1); /* always go to first col */
  1515. term.esc = 0;
  1516. break;
  1517. case 'H': /* HTS -- Horizontal tab stop */
  1518. term.tabs[term.c.x] = 1;
  1519. term.esc = 0;
  1520. break;
  1521. case 'M': /* RI -- Reverse index */
  1522. if(term.c.y == term.top)
  1523. tscrolldown(term.top, 1);
  1524. else
  1525. tmoveto(term.c.x, term.c.y-1);
  1526. term.esc = 0;
  1527. break;
  1528. case 'c': /* RIS -- Reset to inital state */
  1529. treset();
  1530. term.esc = 0;
  1531. xresettitle();
  1532. break;
  1533. case '=': /* DECPAM -- Application keypad */
  1534. term.mode |= MODE_APPKEYPAD;
  1535. term.esc = 0;
  1536. break;
  1537. case '>': /* DECPNM -- Normal keypad */
  1538. term.mode &= ~MODE_APPKEYPAD;
  1539. term.esc = 0;
  1540. break;
  1541. case '7': /* DECSC -- Save Cursor */
  1542. tcursor(CURSOR_SAVE);
  1543. term.esc = 0;
  1544. break;
  1545. case '8': /* DECRC -- Restore Cursor */
  1546. tcursor(CURSOR_LOAD);
  1547. term.esc = 0;
  1548. break;
  1549. case '\\': /* ST -- Stop */
  1550. term.esc = 0;
  1551. break;
  1552. default:
  1553. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1554. (uchar) ascii, isprint(ascii)?ascii:'.');
  1555. term.esc = 0;
  1556. }
  1557. }
  1558. } else {
  1559. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1560. sel.bx = -1;
  1561. switch(ascii) {
  1562. case '\0': /* padding character, do nothing */
  1563. break;
  1564. case '\t':
  1565. tputtab(1);
  1566. break;
  1567. case '\b':
  1568. tmoveto(term.c.x-1, term.c.y);
  1569. break;
  1570. case '\r':
  1571. tmoveto(0, term.c.y);
  1572. break;
  1573. case '\f':
  1574. case '\v':
  1575. case '\n':
  1576. /* go to first col if the mode is set */
  1577. tnewline(IS_SET(MODE_CRLF));
  1578. break;
  1579. case '\a':
  1580. if(!(xw.state & WIN_FOCUSED))
  1581. xseturgency(1);
  1582. break;
  1583. case '\033':
  1584. csireset();
  1585. term.esc = ESC_START;
  1586. break;
  1587. default:
  1588. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1589. tnewline(1); /* always go to first col */
  1590. tsetchar(c);
  1591. if(term.c.x+1 < term.col)
  1592. tmoveto(term.c.x+1, term.c.y);
  1593. else
  1594. term.c.state |= CURSOR_WRAPNEXT;
  1595. }
  1596. }
  1597. }
  1598. int
  1599. tresize(int col, int row) {
  1600. int i, x;
  1601. int minrow = MIN(row, term.row);
  1602. int mincol = MIN(col, term.col);
  1603. int slide = term.c.y - row + 1;
  1604. if(col < 1 || row < 1)
  1605. return 0;
  1606. /* free unneeded rows */
  1607. i = 0;
  1608. if(slide > 0) {
  1609. /* slide screen to keep cursor where we expect it -
  1610. * tscrollup would work here, but we can optimize to
  1611. * memmove because we're freeing the earlier lines */
  1612. for(/* i = 0 */; i < slide; i++) {
  1613. free(term.line[i]);
  1614. free(term.alt[i]);
  1615. }
  1616. memmove(term.line, term.line + slide, row * sizeof(Line));
  1617. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1618. }
  1619. for(i += row; i < term.row; i++) {
  1620. free(term.line[i]);
  1621. free(term.alt[i]);
  1622. }
  1623. /* resize to new height */
  1624. term.line = xrealloc(term.line, row * sizeof(Line));
  1625. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1626. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1627. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1628. /* resize each row to new width, zero-pad if needed */
  1629. for(i = 0; i < minrow; i++) {
  1630. term.dirty[i] = 1;
  1631. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1632. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1633. for(x = mincol; x < col; x++) {
  1634. term.line[i][x].state = 0;
  1635. term.alt[i][x].state = 0;
  1636. }
  1637. }
  1638. /* allocate any new rows */
  1639. for(/* i == minrow */; i < row; i++) {
  1640. term.dirty[i] = 1;
  1641. term.line[i] = calloc(col, sizeof(Glyph));
  1642. term.alt [i] = calloc(col, sizeof(Glyph));
  1643. }
  1644. if(col > term.col) {
  1645. bool *bp = term.tabs + term.col;
  1646. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1647. while(--bp > term.tabs && !*bp)
  1648. /* nothing */ ;
  1649. for(bp += TAB; bp < term.tabs + col; bp += TAB)
  1650. *bp = 1;
  1651. }
  1652. /* update terminal size */
  1653. term.col = col, term.row = row;
  1654. /* make use of the LIMIT in tmoveto */
  1655. tmoveto(term.c.x, term.c.y);
  1656. /* reset scrolling region */
  1657. tsetscroll(0, row-1);
  1658. return (slide > 0);
  1659. }
  1660. void
  1661. xresize(int col, int row) {
  1662. xw.w = MAX(1, 2*BORDER + col * xw.cw);
  1663. xw.h = MAX(1, 2*BORDER + row * xw.ch);
  1664. }
  1665. void
  1666. xloadcols(void) {
  1667. int i, r, g, b;
  1668. XColor color;
  1669. ulong white = WhitePixel(xw.dpy, xw.scr);
  1670. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1671. for(i = 0; i < LEN(colorname); i++) {
  1672. if(!colorname[i])
  1673. continue;
  1674. if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
  1675. dc.col[i] = white;
  1676. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1677. } else
  1678. dc.col[i] = color.pixel;
  1679. }
  1680. /* load colors [16-255] ; same colors as xterm */
  1681. for(i = 16, r = 0; r < 6; r++)
  1682. for(g = 0; g < 6; g++)
  1683. for(b = 0; b < 6; b++) {
  1684. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1685. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1686. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1687. if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1688. dc.col[i] = white;
  1689. fprintf(stderr, "Could not allocate color %d\n", i);
  1690. } else
  1691. dc.col[i] = color.pixel;
  1692. i++;
  1693. }
  1694. for(r = 0; r < 24; r++, i++) {
  1695. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1696. if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1697. dc.col[i] = white;
  1698. fprintf(stderr, "Could not allocate color %d\n", i);
  1699. } else
  1700. dc.col[i] = color.pixel;
  1701. }
  1702. }
  1703. void
  1704. xclear(int x1, int y1, int x2, int y2) {
  1705. XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
  1706. XFillRectangle(xw.dpy, xw.buf, dc.gc,
  1707. BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
  1708. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1709. }
  1710. void
  1711. xhints(void) {
  1712. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1713. XWMHints wm = {.flags = InputHint, .input = 1};
  1714. XSizeHints *sizeh = NULL;
  1715. sizeh = XAllocSizeHints();
  1716. if(xw.isfixed == False) {
  1717. sizeh->flags = PSize | PResizeInc | PBaseSize;
  1718. sizeh->height = xw.h;
  1719. sizeh->width = xw.w;
  1720. sizeh->height_inc = xw.ch;
  1721. sizeh->width_inc = xw.cw;
  1722. sizeh->base_height = 2*BORDER;
  1723. sizeh->base_width = 2*BORDER;
  1724. } else {
  1725. sizeh->flags = PMaxSize | PMinSize;
  1726. sizeh->min_width = sizeh->max_width = xw.fw;
  1727. sizeh->min_height = sizeh->max_height = xw.fh;
  1728. }
  1729. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  1730. XFree(sizeh);
  1731. }
  1732. XFontSet
  1733. xinitfont(char *fontstr) {
  1734. XFontSet set;
  1735. char *def, **missing;
  1736. int n;
  1737. missing = NULL;
  1738. set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
  1739. if(missing) {
  1740. while(n--)
  1741. fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
  1742. XFreeStringList(missing);
  1743. }
  1744. return set;
  1745. }
  1746. void
  1747. xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
  1748. XFontStruct **xfonts;
  1749. char **font_names;
  1750. int i, n;
  1751. *ascent = *descent = *lbearing = *rbearing = 0;
  1752. n = XFontsOfFontSet(set, &xfonts, &font_names);
  1753. for(i = 0; i < n; i++) {
  1754. *ascent = MAX(*ascent, (*xfonts)->ascent);
  1755. *descent = MAX(*descent, (*xfonts)->descent);
  1756. *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
  1757. *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
  1758. xfonts++;
  1759. }
  1760. }
  1761. void
  1762. initfonts(char *fontstr, char *bfontstr, char *ifontstr, char *ibfontstr) {
  1763. if((dc.font.set = xinitfont(fontstr)) == NULL)
  1764. die("Can't load font %s\n", fontstr);
  1765. if((dc.bfont.set = xinitfont(bfontstr)) == NULL)
  1766. die("Can't load bfont %s\n", bfontstr);
  1767. if((dc.ifont.set = xinitfont(ifontstr)) == NULL)
  1768. die("Can't load ifont %s\n", ifontstr);
  1769. if((dc.ibfont.set = xinitfont(ibfontstr)) == NULL)
  1770. die("Can't load ibfont %s\n", ibfontstr);
  1771. xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
  1772. &dc.font.lbearing, &dc.font.rbearing);
  1773. xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
  1774. &dc.bfont.lbearing, &dc.bfont.rbearing);
  1775. xgetfontinfo(dc.ifont.set, &dc.ifont.ascent, &dc.ifont.descent,
  1776. &dc.ifont.lbearing, &dc.ifont.rbearing);
  1777. xgetfontinfo(dc.ibfont.set, &dc.ibfont.ascent, &dc.ibfont.descent,
  1778. &dc.ibfont.lbearing, &dc.ibfont.rbearing);
  1779. }
  1780. void
  1781. xinit(void) {
  1782. XSetWindowAttributes attrs;
  1783. Cursor cursor;
  1784. Window parent;
  1785. int sw, sh, major, minor;
  1786. if(!(xw.dpy = XOpenDisplay(NULL)))
  1787. die("Can't open display\n");
  1788. xw.scr = XDefaultScreen(xw.dpy);
  1789. /* font */
  1790. initfonts(FONT, BOLDFONT, ITALICFONT, ITALICBOLDFONT);
  1791. /* XXX: Assuming same size for bold font */
  1792. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1793. xw.ch = dc.font.ascent + dc.font.descent;
  1794. /* colors */
  1795. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1796. xloadcols();
  1797. /* adjust fixed window geometry */
  1798. if(xw.isfixed) {
  1799. sw = DisplayWidth(xw.dpy, xw.scr);
  1800. sh = DisplayHeight(xw.dpy, xw.scr);
  1801. if(xw.fx < 0)
  1802. xw.fx = sw + xw.fx - xw.fw - 1;
  1803. if(xw.fy < 0)
  1804. xw.fy = sh + xw.fy - xw.fh - 1;
  1805. xw.h = xw.fh;
  1806. xw.w = xw.fw;
  1807. } else {
  1808. /* window - default size */
  1809. xw.h = 2*BORDER + term.row * xw.ch;
  1810. xw.w = 2*BORDER + term.col * xw.cw;
  1811. xw.fx = 0;
  1812. xw.fy = 0;
  1813. }
  1814. attrs.background_pixel = dc.col[DefaultBG];
  1815. attrs.border_pixel = dc.col[DefaultBG];
  1816. attrs.bit_gravity = NorthWestGravity;
  1817. attrs.event_mask = FocusChangeMask | KeyPressMask
  1818. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1819. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  1820. attrs.colormap = xw.cmap;
  1821. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  1822. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  1823. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1824. XDefaultVisual(xw.dpy, xw.scr),
  1825. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1826. | CWColormap,
  1827. &attrs);
  1828. if(!XdbeQueryExtension(xw.dpy, &major, &minor))
  1829. die("Xdbe extension is not present\n");
  1830. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  1831. /* input methods */
  1832. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1833. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1834. | XIMStatusNothing, XNClientWindow, xw.win,
  1835. XNFocusWindow, xw.win, NULL);
  1836. /* gc */
  1837. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1838. /* white cursor, black outline */
  1839. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1840. XDefineCursor(xw.dpy, xw.win, cursor);
  1841. XRecolorCursor(xw.dpy, cursor,
  1842. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1843. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1844. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1845. xresettitle();
  1846. XMapWindow(xw.dpy, xw.win);
  1847. xhints();
  1848. XSync(xw.dpy, 0);
  1849. }
  1850. void
  1851. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1852. int fg = base.fg, bg = base.bg, temp;
  1853. int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1854. XFontSet fontset = dc.font.set;
  1855. int i;
  1856. /* only switch default fg/bg if term is in RV mode */
  1857. if(IS_SET(MODE_REVERSE)) {
  1858. if(fg == DefaultFG)
  1859. fg = DefaultBG;
  1860. if(bg == DefaultBG)
  1861. bg = DefaultFG;
  1862. }
  1863. if(base.mode & ATTR_REVERSE)
  1864. temp = fg, fg = bg, bg = temp;
  1865. if(base.mode & ATTR_BOLD) {
  1866. fg += 8;
  1867. fontset = dc.bfont.set;
  1868. }
  1869. if(base.mode & ATTR_ITALIC)
  1870. fontset = dc.ifont.set;
  1871. if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
  1872. fontset = dc.ibfont.set;
  1873. XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
  1874. XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
  1875. if(base.mode & ATTR_GFX) {
  1876. for(i = 0; i < bytelen; i++) {
  1877. char c = gfx[(uint)s[i] % 256];
  1878. if(c)
  1879. s[i] = c;
  1880. else if(s[i] > 0x5f)
  1881. s[i] -= 0x5f;
  1882. }
  1883. }
  1884. XmbDrawImageString(xw.dpy, xw.buf, fontset, dc.gc, winx, winy, s, bytelen);
  1885. if(base.mode & ATTR_UNDERLINE)
  1886. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1887. }
  1888. /* copy buffer pixmap to screen pixmap */
  1889. void
  1890. xcopy() {
  1891. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  1892. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  1893. }
  1894. void
  1895. xdrawcursor(void) {
  1896. static int oldx = 0;
  1897. static int oldy = 0;
  1898. int sl;
  1899. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1900. LIMIT(oldx, 0, term.col-1);
  1901. LIMIT(oldy, 0, term.row-1);
  1902. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1903. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1904. /* remove the old cursor */
  1905. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1906. sl = utf8size(term.line[oldy][oldx].c);
  1907. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1908. } else
  1909. xclear(oldx, oldy, oldx, oldy);
  1910. xcopy();
  1911. /* draw the new one */
  1912. if(!(term.c.state & CURSOR_HIDE)) {
  1913. if(!(xw.state & WIN_FOCUSED))
  1914. g.bg = DefaultUCS;
  1915. if(IS_SET(MODE_REVERSE))
  1916. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  1917. sl = utf8size(g.c);
  1918. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1919. oldx = term.c.x, oldy = term.c.y;
  1920. }
  1921. xcopy();
  1922. }
  1923. void
  1924. xresettitle(void) {
  1925. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1926. }
  1927. void
  1928. redraw(void) {
  1929. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  1930. tfulldirt();
  1931. draw();
  1932. XSync(xw.dpy, False); /* necessary for a good tput flash */
  1933. nanosleep(&tv, NULL);
  1934. }
  1935. void
  1936. draw() {
  1937. drawregion(0, 0, term.col, term.row);
  1938. xcopy();
  1939. gettimeofday(&xw.lastdraw, NULL);
  1940. }
  1941. void
  1942. drawregion(int x1, int y1, int x2, int y2) {
  1943. int ic, ib, x, y, ox, sl;
  1944. Glyph base, new;
  1945. char buf[DRAW_BUF_SIZ];
  1946. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
  1947. if((sel.alt && !alt) || (!sel.alt && alt))
  1948. ena_sel = 0;
  1949. if(!(xw.state & WIN_VISIBLE))
  1950. return;
  1951. for(y = y1; y < y2; y++) {
  1952. if(!term.dirty[y])
  1953. continue;
  1954. xclear(0, y, term.col, y);
  1955. term.dirty[y] = 0;
  1956. base = term.line[y][0];
  1957. ic = ib = ox = 0;
  1958. for(x = x1; x < x2; x++) {
  1959. new = term.line[y][x];
  1960. if(ena_sel && *(new.c) && selected(x, y))
  1961. new.mode ^= ATTR_REVERSE;
  1962. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1963. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1964. xdraws(buf, base, ox, y, ic, ib);
  1965. ic = ib = 0;
  1966. }
  1967. if(new.state & GLYPH_SET) {
  1968. if(ib == 0) {
  1969. ox = x;
  1970. base = new;
  1971. }
  1972. sl = utf8size(new.c);
  1973. memcpy(buf+ib, new.c, sl);
  1974. ib += sl;
  1975. ++ic;
  1976. }
  1977. }
  1978. if(ib > 0)
  1979. xdraws(buf, base, ox, y, ic, ib);
  1980. }
  1981. xdrawcursor();
  1982. }
  1983. void
  1984. expose(XEvent *ev) {
  1985. XExposeEvent *e = &ev->xexpose;
  1986. if(xw.state & WIN_REDRAW) {
  1987. if(!e->count)
  1988. xw.state &= ~WIN_REDRAW;
  1989. }
  1990. xcopy();
  1991. }
  1992. void
  1993. visibility(XEvent *ev) {
  1994. XVisibilityEvent *e = &ev->xvisibility;
  1995. if(e->state == VisibilityFullyObscured)
  1996. xw.state &= ~WIN_VISIBLE;
  1997. else if(!(xw.state & WIN_VISIBLE))
  1998. /* need a full redraw for next Expose, not just a buf copy */
  1999. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2000. }
  2001. void
  2002. unmap(XEvent *ev) {
  2003. xw.state &= ~WIN_VISIBLE;
  2004. }
  2005. void
  2006. xseturgency(int add) {
  2007. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2008. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2009. XSetWMHints(xw.dpy, xw.win, h);
  2010. XFree(h);
  2011. }
  2012. void
  2013. focus(XEvent *ev) {
  2014. if(ev->type == FocusIn) {
  2015. xw.state |= WIN_FOCUSED;
  2016. xseturgency(0);
  2017. } else
  2018. xw.state &= ~WIN_FOCUSED;
  2019. draw();
  2020. }
  2021. char*
  2022. kmap(KeySym k, uint state) {
  2023. int i;
  2024. state &= ~Mod2Mask;
  2025. for(i = 0; i < LEN(key); i++) {
  2026. uint mask = key[i].mask;
  2027. if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
  2028. return (char*)key[i].s;
  2029. }
  2030. return NULL;
  2031. }
  2032. void
  2033. kpress(XEvent *ev) {
  2034. XKeyEvent *e = &ev->xkey;
  2035. KeySym ksym;
  2036. char buf[32];
  2037. char *customkey;
  2038. int len;
  2039. int meta;
  2040. int shift;
  2041. Status status;
  2042. meta = e->state & Mod1Mask;
  2043. shift = e->state & ShiftMask;
  2044. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  2045. /* 1. custom keys from config.h */
  2046. if((customkey = kmap(ksym, e->state)))
  2047. ttywrite(customkey, strlen(customkey));
  2048. /* 2. hardcoded (overrides X lookup) */
  2049. else
  2050. switch(ksym) {
  2051. case XK_Up:
  2052. case XK_Down:
  2053. case XK_Left:
  2054. case XK_Right:
  2055. /* XXX: shift up/down doesn't work */
  2056. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
  2057. ttywrite(buf, 3);
  2058. break;
  2059. case XK_Insert:
  2060. if(shift)
  2061. selpaste();
  2062. break;
  2063. case XK_Return:
  2064. if(IS_SET(MODE_CRLF))
  2065. ttywrite("\r\n", 2);
  2066. else
  2067. ttywrite("\r", 1);
  2068. break;
  2069. /* 3. X lookup */
  2070. default:
  2071. if(len > 0) {
  2072. if(meta && len == 1)
  2073. ttywrite("\033", 1);
  2074. ttywrite(buf, len);
  2075. }
  2076. break;
  2077. }
  2078. }
  2079. void
  2080. cmessage(XEvent *e) {
  2081. /* See xembed specs
  2082. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2083. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2084. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2085. xw.state |= WIN_FOCUSED;
  2086. xseturgency(0);
  2087. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2088. xw.state &= ~WIN_FOCUSED;
  2089. }
  2090. draw();
  2091. }
  2092. }
  2093. void
  2094. resize(XEvent *e) {
  2095. int col, row;
  2096. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2097. return;
  2098. xw.w = e->xconfigure.width;
  2099. xw.h = e->xconfigure.height;
  2100. col = (xw.w - 2*BORDER) / xw.cw;
  2101. row = (xw.h - 2*BORDER) / xw.ch;
  2102. if(col == term.col && row == term.row)
  2103. return;
  2104. if(tresize(col, row))
  2105. draw();
  2106. xresize(col, row);
  2107. ttyresize(col, row);
  2108. }
  2109. bool
  2110. last_draw_too_old(void) {
  2111. struct timeval now;
  2112. gettimeofday(&now, NULL);
  2113. return TIMEDIFF(now, xw.lastdraw) >= DRAW_TIMEOUT/1000;
  2114. }
  2115. void
  2116. run(void) {
  2117. XEvent ev;
  2118. fd_set rfd;
  2119. int xfd = XConnectionNumber(xw.dpy);
  2120. struct timeval timeout = {0};
  2121. bool stuff_to_print = 0;
  2122. for(;;) {
  2123. FD_ZERO(&rfd);
  2124. FD_SET(cmdfd, &rfd);
  2125. FD_SET(xfd, &rfd);
  2126. timeout.tv_sec = 0;
  2127. timeout.tv_usec = SELECT_TIMEOUT;
  2128. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, &timeout) < 0) {
  2129. if(errno == EINTR)
  2130. continue;
  2131. die("select failed: %s\n", SERRNO);
  2132. }
  2133. if(FD_ISSET(cmdfd, &rfd)) {
  2134. ttyread();
  2135. stuff_to_print = 1;
  2136. }
  2137. if(stuff_to_print && last_draw_too_old()) {
  2138. stuff_to_print = 0;
  2139. draw();
  2140. }
  2141. while(XPending(xw.dpy)) {
  2142. XNextEvent(xw.dpy, &ev);
  2143. if(XFilterEvent(&ev, xw.win))
  2144. continue;
  2145. if(handler[ev.type])
  2146. (handler[ev.type])(&ev);
  2147. }
  2148. }
  2149. }
  2150. int
  2151. main(int argc, char *argv[]) {
  2152. int i, bitm, xr, yr;
  2153. unsigned int wr, hr;
  2154. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2155. xw.isfixed = False;
  2156. for(i = 1; i < argc; i++) {
  2157. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2158. case 't':
  2159. if(++i < argc) opt_title = argv[i];
  2160. break;
  2161. case 'c':
  2162. if(++i < argc) opt_class = argv[i];
  2163. break;
  2164. case 'w':
  2165. if(++i < argc) opt_embed = argv[i];
  2166. break;
  2167. case 'f':
  2168. if(++i < argc) opt_io = argv[i];
  2169. break;
  2170. case 'e':
  2171. /* eat every remaining arguments */
  2172. if(++i < argc) opt_cmd = &argv[i];
  2173. goto run;
  2174. case 'g':
  2175. if(++i >= argc)
  2176. break;
  2177. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2178. if(bitm & XValue)
  2179. xw.fx = xr;
  2180. if(bitm & YValue)
  2181. xw.fy = yr;
  2182. if(bitm & WidthValue)
  2183. xw.fw = (int)wr;
  2184. if(bitm & HeightValue)
  2185. xw.fh = (int)hr;
  2186. if(bitm & XNegative && xw.fx == 0)
  2187. xw.fx = -1;
  2188. if(bitm & XNegative && xw.fy == 0)
  2189. xw.fy = -1;
  2190. if(xw.fh != 0 && xw.fw != 0)
  2191. xw.isfixed = True;
  2192. break;
  2193. case 'v':
  2194. default:
  2195. die(USAGE);
  2196. }
  2197. }
  2198. run:
  2199. setlocale(LC_CTYPE, "");
  2200. tnew(80, 24);
  2201. ttynew();
  2202. xinit();
  2203. selinit();
  2204. run();
  2205. return 0;
  2206. }