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.

2396 lines
53 KiB

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