My build of suckless st terminal
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.

2398 lines
53 KiB

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