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.

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