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.

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