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.

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