Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2368 lines
53 KiB

12 years ago
13 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
14 years ago
13 years ago
13 years ago
14 years ago
13 years ago
13 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
13 years ago
  1. /* See LICENSE for licence details. */
  2. #define _XOPEN_SOURCE 600
  3. #include <ctype.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <limits.h>
  7. #include <locale.h>
  8. #include <stdarg.h>
  9. #include <stdbool.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <signal.h>
  14. #include <sys/ioctl.h>
  15. #include <sys/select.h>
  16. #include <sys/stat.h>
  17. #include <sys/time.h>
  18. #include <sys/types.h>
  19. #include <sys/wait.h>
  20. #include <time.h>
  21. #include <unistd.h>
  22. #include <X11/Xatom.h>
  23. #include <X11/Xlib.h>
  24. #include <X11/Xutil.h>
  25. #include <X11/cursorfont.h>
  26. #include <X11/keysym.h>
  27. #include <X11/extensions/Xdbe.h>
  28. #if defined(__linux)
  29. #include <pty.h>
  30. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  31. #include <util.h>
  32. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  33. #include <libutil.h>
  34. #endif
  35. #define USAGE \
  36. "st " VERSION " (c) 2010-2012 st engineers\n" \
  37. "usage: st [-t title] [-c class] [-g geometry]" \
  38. " [-w windowid] [-v] [-f file] [-e command...]\n"
  39. /* XEMBED messages */
  40. #define XEMBED_FOCUS_IN 4
  41. #define XEMBED_FOCUS_OUT 5
  42. /* Arbitrary sizes */
  43. #define ESC_BUF_SIZ 256
  44. #define ESC_ARG_SIZ 16
  45. #define STR_BUF_SIZ 256
  46. #define STR_ARG_SIZ 16
  47. #define DRAW_BUF_SIZ 1024
  48. #define UTF_SIZ 4
  49. #define XK_NO_MOD UINT_MAX
  50. #define XK_ANY_MOD 0
  51. #define SELECT_TIMEOUT (20*1000) /* 20 ms */
  52. #define DRAW_TIMEOUT (20*1000) /* 20 ms */
  53. #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
  54. #define SERRNO strerror(errno)
  55. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  56. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  57. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  58. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  59. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  60. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  61. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  62. #define IS_SET(flag) (term.mode & (flag))
  63. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
  64. #define X2COL(x) (((x) - BORDER)/xw.cw)
  65. #define Y2ROW(y) (((y) - BORDER)/xw.ch)
  66. enum glyph_attribute {
  67. ATTR_NULL = 0,
  68. ATTR_REVERSE = 1,
  69. ATTR_UNDERLINE = 2,
  70. ATTR_BOLD = 4,
  71. ATTR_GFX = 8,
  72. };
  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 = w.ws_ypixel = 0;
  754. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  755. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  756. }
  757. void
  758. tsetdirt(int top, int bot)
  759. {
  760. int i;
  761. LIMIT(top, 0, term.row-1);
  762. LIMIT(bot, 0, term.row-1);
  763. for(i = top; i <= bot; i++)
  764. term.dirty[i] = 1;
  765. }
  766. void
  767. tfulldirt(void)
  768. {
  769. tsetdirt(0, term.row-1);
  770. }
  771. void
  772. tcursor(int mode) {
  773. static TCursor c;
  774. if(mode == CURSOR_SAVE)
  775. c = term.c;
  776. else if(mode == CURSOR_LOAD)
  777. term.c = c, tmoveto(c.x, c.y);
  778. }
  779. void
  780. treset(void) {
  781. unsigned i;
  782. term.c = (TCursor){{
  783. .mode = ATTR_NULL,
  784. .fg = DefaultFG,
  785. .bg = DefaultBG
  786. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  787. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  788. for(i = TAB; i < term.col; i += TAB)
  789. term.tabs[i] = 1;
  790. term.top = 0, term.bot = term.row - 1;
  791. term.mode = MODE_WRAP;
  792. tclearregion(0, 0, term.col-1, term.row-1);
  793. }
  794. void
  795. tnew(int col, int row) {
  796. /* set screen size */
  797. term.row = row, term.col = col;
  798. term.line = malloc(term.row * sizeof(Line));
  799. term.alt = malloc(term.row * sizeof(Line));
  800. term.dirty = malloc(term.row * sizeof(*term.dirty));
  801. term.tabs = malloc(term.col * sizeof(*term.tabs));
  802. for(row = 0; row < term.row; row++) {
  803. term.line[row] = malloc(term.col * sizeof(Glyph));
  804. term.alt [row] = malloc(term.col * sizeof(Glyph));
  805. term.dirty[row] = 0;
  806. }
  807. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  808. /* setup screen */
  809. treset();
  810. }
  811. void
  812. tswapscreen(void) {
  813. Line* tmp = term.line;
  814. term.line = term.alt;
  815. term.alt = tmp;
  816. term.mode ^= MODE_ALTSCREEN;
  817. tfulldirt();
  818. }
  819. void
  820. tscrolldown(int orig, int n) {
  821. int i;
  822. Line temp;
  823. LIMIT(n, 0, term.bot-orig+1);
  824. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  825. for(i = term.bot; i >= orig+n; i--) {
  826. temp = term.line[i];
  827. term.line[i] = term.line[i-n];
  828. term.line[i-n] = temp;
  829. term.dirty[i] = 1;
  830. term.dirty[i-n] = 1;
  831. }
  832. selscroll(orig, n);
  833. }
  834. void
  835. tscrollup(int orig, int n) {
  836. int i;
  837. Line temp;
  838. LIMIT(n, 0, term.bot-orig+1);
  839. tclearregion(0, orig, term.col-1, orig+n-1);
  840. for(i = orig; i <= term.bot-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. selscroll(int orig, int n) {
  851. if(sel.bx == -1)
  852. return;
  853. if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
  854. if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
  855. sel.bx = -1;
  856. return;
  857. }
  858. if(sel.by < term.top) {
  859. sel.by = term.top;
  860. sel.bx = 0;
  861. }
  862. if(sel.ey > term.bot) {
  863. sel.ey = term.bot;
  864. sel.ex = term.col;
  865. }
  866. sel.b.y = sel.by, sel.b.x = sel.bx;
  867. sel.e.y = sel.ey, sel.e.x = sel.ex;
  868. }
  869. }
  870. void
  871. tnewline(int first_col) {
  872. int y = term.c.y;
  873. if(y == term.bot)
  874. tscrollup(term.top, 1);
  875. else
  876. y++;
  877. tmoveto(first_col ? 0 : term.c.x, y);
  878. }
  879. void
  880. csiparse(void) {
  881. /* int noarg = 1; */
  882. char *p = csiescseq.buf;
  883. csiescseq.narg = 0;
  884. if(*p == '?')
  885. csiescseq.priv = 1, p++;
  886. while(p < csiescseq.buf+csiescseq.len) {
  887. while(isdigit(*p)) {
  888. csiescseq.arg[csiescseq.narg] *= 10;
  889. csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
  890. }
  891. if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
  892. csiescseq.narg++, p++;
  893. else {
  894. csiescseq.mode = *p;
  895. csiescseq.narg++;
  896. return;
  897. }
  898. }
  899. }
  900. void
  901. tmoveto(int x, int y) {
  902. LIMIT(x, 0, term.col-1);
  903. LIMIT(y, 0, term.row-1);
  904. term.c.state &= ~CURSOR_WRAPNEXT;
  905. term.c.x = x;
  906. term.c.y = y;
  907. }
  908. void
  909. tsetchar(char *c) {
  910. term.dirty[term.c.y] = 1;
  911. term.line[term.c.y][term.c.x] = term.c.attr;
  912. memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
  913. term.line[term.c.y][term.c.x].state |= GLYPH_SET;
  914. }
  915. void
  916. tclearregion(int x1, int y1, int x2, int y2) {
  917. int x, y, temp;
  918. if(x1 > x2)
  919. temp = x1, x1 = x2, x2 = temp;
  920. if(y1 > y2)
  921. temp = y1, y1 = y2, y2 = temp;
  922. LIMIT(x1, 0, term.col-1);
  923. LIMIT(x2, 0, term.col-1);
  924. LIMIT(y1, 0, term.row-1);
  925. LIMIT(y2, 0, term.row-1);
  926. for(y = y1; y <= y2; y++) {
  927. term.dirty[y] = 1;
  928. for(x = x1; x <= x2; x++)
  929. term.line[y][x].state = 0;
  930. }
  931. }
  932. void
  933. tdeletechar(int n) {
  934. int src = term.c.x + n;
  935. int dst = term.c.x;
  936. int size = term.col - src;
  937. term.dirty[term.c.y] = 1;
  938. if(src >= term.col) {
  939. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  940. return;
  941. }
  942. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  943. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  944. }
  945. void
  946. tinsertblank(int n) {
  947. int src = term.c.x;
  948. int dst = src + n;
  949. int size = term.col - dst;
  950. term.dirty[term.c.y] = 1;
  951. if(dst >= term.col) {
  952. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  953. return;
  954. }
  955. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  956. tclearregion(src, term.c.y, dst - 1, term.c.y);
  957. }
  958. void
  959. tinsertblankline(int n) {
  960. if(term.c.y < term.top || term.c.y > term.bot)
  961. return;
  962. tscrolldown(term.c.y, n);
  963. }
  964. void
  965. tdeleteline(int n) {
  966. if(term.c.y < term.top || term.c.y > term.bot)
  967. return;
  968. tscrollup(term.c.y, n);
  969. }
  970. void
  971. tsetattr(int *attr, int l) {
  972. int i;
  973. for(i = 0; i < l; i++) {
  974. switch(attr[i]) {
  975. case 0:
  976. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
  977. term.c.attr.fg = DefaultFG;
  978. term.c.attr.bg = DefaultBG;
  979. break;
  980. case 1:
  981. term.c.attr.mode |= ATTR_BOLD;
  982. break;
  983. case 3: /* enter standout (highlight) mode TODO: make it italic */
  984. term.c.attr.mode |= ATTR_REVERSE;
  985. break;
  986. case 4:
  987. term.c.attr.mode |= ATTR_UNDERLINE;
  988. break;
  989. case 7:
  990. term.c.attr.mode |= ATTR_REVERSE;
  991. break;
  992. case 22:
  993. term.c.attr.mode &= ~ATTR_BOLD;
  994. break;
  995. case 23: /* leave standout (highlight) mode TODO: make it italic */
  996. term.c.attr.mode &= ~ATTR_REVERSE;
  997. break;
  998. case 24:
  999. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1000. break;
  1001. case 27:
  1002. term.c.attr.mode &= ~ATTR_REVERSE;
  1003. break;
  1004. case 38:
  1005. if(i + 2 < l && attr[i + 1] == 5) {
  1006. i += 2;
  1007. if(BETWEEN(attr[i], 0, 255))
  1008. term.c.attr.fg = attr[i];
  1009. else
  1010. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
  1011. }
  1012. else
  1013. fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
  1014. break;
  1015. case 39:
  1016. term.c.attr.fg = DefaultFG;
  1017. break;
  1018. case 48:
  1019. if(i + 2 < l && attr[i + 1] == 5) {
  1020. i += 2;
  1021. if(BETWEEN(attr[i], 0, 255))
  1022. term.c.attr.bg = attr[i];
  1023. else
  1024. fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
  1025. }
  1026. else
  1027. fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
  1028. break;
  1029. case 49:
  1030. term.c.attr.bg = DefaultBG;
  1031. break;
  1032. default:
  1033. if(BETWEEN(attr[i], 30, 37))
  1034. term.c.attr.fg = attr[i] - 30;
  1035. else if(BETWEEN(attr[i], 40, 47))
  1036. term.c.attr.bg = attr[i] - 40;
  1037. else if(BETWEEN(attr[i], 90, 97))
  1038. term.c.attr.fg = attr[i] - 90 + 8;
  1039. else if(BETWEEN(attr[i], 100, 107))
  1040. term.c.attr.fg = attr[i] - 100 + 8;
  1041. else
  1042. fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
  1043. break;
  1044. }
  1045. }
  1046. }
  1047. void
  1048. tsetscroll(int t, int b) {
  1049. int temp;
  1050. LIMIT(t, 0, term.row-1);
  1051. LIMIT(b, 0, term.row-1);
  1052. if(t > b) {
  1053. temp = t;
  1054. t = b;
  1055. b = temp;
  1056. }
  1057. term.top = t;
  1058. term.bot = b;
  1059. }
  1060. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1061. void
  1062. tsetmode(bool priv, bool set, int *args, int narg) {
  1063. int *lim, mode;
  1064. for(lim = args + narg; args < lim; ++args) {
  1065. if(priv) {
  1066. switch(*args) {
  1067. case 1:
  1068. MODBIT(term.mode, set, MODE_APPKEYPAD);
  1069. break;
  1070. case 5: /* DECSCNM -- Reverve video */
  1071. mode = term.mode;
  1072. MODBIT(term.mode,set, MODE_REVERSE);
  1073. if(mode != term.mode)
  1074. redraw();
  1075. break;
  1076. case 7:
  1077. MODBIT(term.mode, set, MODE_WRAP);
  1078. break;
  1079. case 20:
  1080. MODBIT(term.mode, set, MODE_CRLF);
  1081. break;
  1082. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1083. break;
  1084. case 25:
  1085. MODBIT(term.c.state, !set, CURSOR_HIDE);
  1086. break;
  1087. case 1000: /* 1000,1002: enable xterm mouse report */
  1088. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1089. break;
  1090. case 1002:
  1091. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1092. break;
  1093. case 1049: /* = 1047 and 1048 */
  1094. case 47:
  1095. case 1047:
  1096. if(IS_SET(MODE_ALTSCREEN))
  1097. tclearregion(0, 0, term.col-1, term.row-1);
  1098. if((set && !IS_SET(MODE_ALTSCREEN)) ||
  1099. (!set && IS_SET(MODE_ALTSCREEN))) {
  1100. tswapscreen();
  1101. }
  1102. if(*args != 1049)
  1103. break;
  1104. /* pass through */
  1105. case 1048:
  1106. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1107. break;
  1108. default:
  1109. fprintf(stderr,
  1110. "erresc: unknown private set/reset mode %d\n",
  1111. *args);
  1112. break;
  1113. }
  1114. } else {
  1115. switch(*args) {
  1116. case 4:
  1117. MODBIT(term.mode, set, MODE_INSERT);
  1118. break;
  1119. default:
  1120. fprintf(stderr,
  1121. "erresc: unknown set/reset mode %d\n",
  1122. *args);
  1123. break;
  1124. }
  1125. }
  1126. }
  1127. }
  1128. #undef MODBIT
  1129. void
  1130. csihandle(void) {
  1131. switch(csiescseq.mode) {
  1132. default:
  1133. unknown:
  1134. fprintf(stderr, "erresc: unknown csi ");
  1135. csidump();
  1136. /* die(""); */
  1137. break;
  1138. case '@': /* ICH -- Insert <n> blank char */
  1139. DEFAULT(csiescseq.arg[0], 1);
  1140. tinsertblank(csiescseq.arg[0]);
  1141. break;
  1142. case 'A': /* CUU -- Cursor <n> Up */
  1143. case 'e':
  1144. DEFAULT(csiescseq.arg[0], 1);
  1145. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1146. break;
  1147. case 'B': /* CUD -- Cursor <n> Down */
  1148. DEFAULT(csiescseq.arg[0], 1);
  1149. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1150. break;
  1151. case 'C': /* CUF -- Cursor <n> Forward */
  1152. case 'a':
  1153. DEFAULT(csiescseq.arg[0], 1);
  1154. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1155. break;
  1156. case 'D': /* CUB -- Cursor <n> Backward */
  1157. DEFAULT(csiescseq.arg[0], 1);
  1158. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1159. break;
  1160. case 'E': /* CNL -- Cursor <n> Down and first col */
  1161. DEFAULT(csiescseq.arg[0], 1);
  1162. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1163. break;
  1164. case 'F': /* CPL -- Cursor <n> Up and first col */
  1165. DEFAULT(csiescseq.arg[0], 1);
  1166. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1167. break;
  1168. case 'g': /* TBC -- Tabulation clear */
  1169. switch (csiescseq.arg[0]) {
  1170. case 0: /* clear current tab stop */
  1171. term.tabs[term.c.x] = 0;
  1172. break;
  1173. case 3: /* clear all the tabs */
  1174. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1175. break;
  1176. default:
  1177. goto unknown;
  1178. }
  1179. break;
  1180. case 'G': /* CHA -- Move to <col> */
  1181. case '`': /* HPA */
  1182. DEFAULT(csiescseq.arg[0], 1);
  1183. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1184. break;
  1185. case 'H': /* CUP -- Move to <row> <col> */
  1186. case 'f': /* HVP */
  1187. DEFAULT(csiescseq.arg[0], 1);
  1188. DEFAULT(csiescseq.arg[1], 1);
  1189. tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1190. break;
  1191. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1192. DEFAULT(csiescseq.arg[0], 1);
  1193. while(csiescseq.arg[0]--)
  1194. tputtab(1);
  1195. break;
  1196. case 'J': /* ED -- Clear screen */
  1197. sel.bx = -1;
  1198. switch(csiescseq.arg[0]) {
  1199. case 0: /* below */
  1200. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1201. if(term.c.y < term.row-1)
  1202. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  1203. break;
  1204. case 1: /* above */
  1205. if(term.c.y > 1)
  1206. tclearregion(0, 0, term.col-1, term.c.y-1);
  1207. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1208. break;
  1209. case 2: /* all */
  1210. tclearregion(0, 0, term.col-1, term.row-1);
  1211. break;
  1212. default:
  1213. goto unknown;
  1214. }
  1215. break;
  1216. case 'K': /* EL -- Clear line */
  1217. switch(csiescseq.arg[0]) {
  1218. case 0: /* right */
  1219. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1220. break;
  1221. case 1: /* left */
  1222. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1223. break;
  1224. case 2: /* all */
  1225. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1226. break;
  1227. }
  1228. break;
  1229. case 'S': /* SU -- Scroll <n> line up */
  1230. DEFAULT(csiescseq.arg[0], 1);
  1231. tscrollup(term.top, csiescseq.arg[0]);
  1232. break;
  1233. case 'T': /* SD -- Scroll <n> line down */
  1234. DEFAULT(csiescseq.arg[0], 1);
  1235. tscrolldown(term.top, csiescseq.arg[0]);
  1236. break;
  1237. case 'L': /* IL -- Insert <n> blank lines */
  1238. DEFAULT(csiescseq.arg[0], 1);
  1239. tinsertblankline(csiescseq.arg[0]);
  1240. break;
  1241. case 'l': /* RM -- Reset Mode */
  1242. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1243. break;
  1244. case 'M': /* DL -- Delete <n> lines */
  1245. DEFAULT(csiescseq.arg[0], 1);
  1246. tdeleteline(csiescseq.arg[0]);
  1247. break;
  1248. case 'X': /* ECH -- Erase <n> char */
  1249. DEFAULT(csiescseq.arg[0], 1);
  1250. tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
  1251. break;
  1252. case 'P': /* DCH -- Delete <n> char */
  1253. DEFAULT(csiescseq.arg[0], 1);
  1254. tdeletechar(csiescseq.arg[0]);
  1255. break;
  1256. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1257. DEFAULT(csiescseq.arg[0], 1);
  1258. while(csiescseq.arg[0]--)
  1259. tputtab(0);
  1260. break;
  1261. case 'd': /* VPA -- Move to <row> */
  1262. DEFAULT(csiescseq.arg[0], 1);
  1263. tmoveto(term.c.x, csiescseq.arg[0]-1);
  1264. break;
  1265. case 'h': /* SM -- Set terminal mode */
  1266. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1267. break;
  1268. case 'm': /* SGR -- Terminal attribute (color) */
  1269. tsetattr(csiescseq.arg, csiescseq.narg);
  1270. break;
  1271. case 'r': /* DECSTBM -- Set Scrolling Region */
  1272. if(csiescseq.priv)
  1273. goto unknown;
  1274. else {
  1275. DEFAULT(csiescseq.arg[0], 1);
  1276. DEFAULT(csiescseq.arg[1], term.row);
  1277. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1278. tmoveto(0, 0);
  1279. }
  1280. break;
  1281. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1282. tcursor(CURSOR_SAVE);
  1283. break;
  1284. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1285. tcursor(CURSOR_LOAD);
  1286. break;
  1287. }
  1288. }
  1289. void
  1290. csidump(void) {
  1291. int i;
  1292. printf("ESC[");
  1293. for(i = 0; i < csiescseq.len; i++) {
  1294. uint c = csiescseq.buf[i] & 0xff;
  1295. if(isprint(c)) putchar(c);
  1296. else if(c == '\n') printf("(\\n)");
  1297. else if(c == '\r') printf("(\\r)");
  1298. else if(c == 0x1b) printf("(\\e)");
  1299. else printf("(%02x)", c);
  1300. }
  1301. putchar('\n');
  1302. }
  1303. void
  1304. csireset(void) {
  1305. memset(&csiescseq, 0, sizeof(csiescseq));
  1306. }
  1307. void
  1308. strhandle(void) {
  1309. char *p;
  1310. /*
  1311. * TODO: make this being useful in case of color palette change.
  1312. */
  1313. strparse();
  1314. p = strescseq.buf;
  1315. switch(strescseq.type) {
  1316. case ']': /* OSC -- Operating System Command */
  1317. switch(p[0]) {
  1318. case '0':
  1319. case '1':
  1320. case '2':
  1321. /*
  1322. * TODO: Handle special chars in string, like umlauts.
  1323. */
  1324. if(p[1] == ';') {
  1325. XStoreName(xw.dpy, xw.win, strescseq.buf+2);
  1326. }
  1327. break;
  1328. case ';':
  1329. XStoreName(xw.dpy, xw.win, strescseq.buf+1);
  1330. break;
  1331. case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
  1332. break;
  1333. default:
  1334. fprintf(stderr, "erresc: unknown str ");
  1335. strdump();
  1336. break;
  1337. }
  1338. break;
  1339. case 'P': /* DSC -- Device Control String */
  1340. case '_': /* APC -- Application Program Command */
  1341. case '^': /* PM -- Privacy Message */
  1342. default:
  1343. fprintf(stderr, "erresc: unknown str ");
  1344. strdump();
  1345. /* die(""); */
  1346. break;
  1347. }
  1348. }
  1349. void
  1350. strparse(void) {
  1351. /*
  1352. * TODO: Implement parsing like for CSI when required.
  1353. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1354. */
  1355. return;
  1356. }
  1357. void
  1358. strdump(void) {
  1359. int i;
  1360. printf("ESC%c", strescseq.type);
  1361. for(i = 0; i < strescseq.len; i++) {
  1362. uint c = strescseq.buf[i] & 0xff;
  1363. if(isprint(c)) putchar(c);
  1364. else if(c == '\n') printf("(\\n)");
  1365. else if(c == '\r') printf("(\\r)");
  1366. else if(c == 0x1b) printf("(\\e)");
  1367. else printf("(%02x)", c);
  1368. }
  1369. printf("ESC\\\n");
  1370. }
  1371. void
  1372. strreset(void) {
  1373. memset(&strescseq, 0, sizeof(strescseq));
  1374. }
  1375. void
  1376. tputtab(bool forward) {
  1377. unsigned x = term.c.x;
  1378. if(forward) {
  1379. if(x == term.col)
  1380. return;
  1381. for(++x; x < term.col && !term.tabs[x]; ++x)
  1382. /* nothing */ ;
  1383. } else {
  1384. if(x == 0)
  1385. return;
  1386. for(--x; x > 0 && !term.tabs[x]; --x)
  1387. /* nothing */ ;
  1388. }
  1389. tmoveto(x, term.c.y);
  1390. }
  1391. void
  1392. tputc(char *c) {
  1393. char ascii = *c;
  1394. if(fileio)
  1395. putc(ascii, fileio);
  1396. if(term.esc & ESC_START) {
  1397. if(term.esc & ESC_CSI) {
  1398. csiescseq.buf[csiescseq.len++] = ascii;
  1399. if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
  1400. term.esc = 0;
  1401. csiparse(), csihandle();
  1402. }
  1403. } else if(term.esc & ESC_STR) {
  1404. switch(ascii) {
  1405. case '\033':
  1406. term.esc = ESC_START | ESC_STR_END;
  1407. break;
  1408. case '\a': /* backwards compatibility to xterm */
  1409. term.esc = 0;
  1410. strhandle();
  1411. break;
  1412. default:
  1413. strescseq.buf[strescseq.len++] = ascii;
  1414. if(strescseq.len+1 >= STR_BUF_SIZ) {
  1415. term.esc = 0;
  1416. strhandle();
  1417. }
  1418. }
  1419. } else if(term.esc & ESC_STR_END) {
  1420. term.esc = 0;
  1421. if(ascii == '\\')
  1422. strhandle();
  1423. } else if(term.esc & ESC_ALTCHARSET) {
  1424. switch(ascii) {
  1425. case '0': /* Line drawing crap */
  1426. term.c.attr.mode |= ATTR_GFX;
  1427. break;
  1428. case 'B': /* Back to regular text */
  1429. term.c.attr.mode &= ~ATTR_GFX;
  1430. break;
  1431. default:
  1432. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1433. }
  1434. term.esc = 0;
  1435. } else {
  1436. switch(ascii) {
  1437. case '[':
  1438. term.esc |= ESC_CSI;
  1439. break;
  1440. case 'P': /* DCS -- Device Control String */
  1441. case '_': /* APC -- Application Program Command */
  1442. case '^': /* PM -- Privacy Message */
  1443. case ']': /* OSC -- Operating System Command */
  1444. strreset();
  1445. strescseq.type = ascii;
  1446. term.esc |= ESC_STR;
  1447. break;
  1448. case '(':
  1449. term.esc |= ESC_ALTCHARSET;
  1450. break;
  1451. case 'D': /* IND -- Linefeed */
  1452. if(term.c.y == term.bot)
  1453. tscrollup(term.top, 1);
  1454. else
  1455. tmoveto(term.c.x, term.c.y+1);
  1456. term.esc = 0;
  1457. break;
  1458. case 'E': /* NEL -- Next line */
  1459. tnewline(1); /* always go to first col */
  1460. term.esc = 0;
  1461. break;
  1462. case 'H': /* HTS -- Horizontal tab stop */
  1463. term.tabs[term.c.x] = 1;
  1464. term.esc = 0;
  1465. break;
  1466. case 'M': /* RI -- Reverse index */
  1467. if(term.c.y == term.top)
  1468. tscrolldown(term.top, 1);
  1469. else
  1470. tmoveto(term.c.x, term.c.y-1);
  1471. term.esc = 0;
  1472. break;
  1473. case 'c': /* RIS -- Reset to inital state */
  1474. treset();
  1475. term.esc = 0;
  1476. break;
  1477. case '=': /* DECPAM -- Application keypad */
  1478. term.mode |= MODE_APPKEYPAD;
  1479. term.esc = 0;
  1480. break;
  1481. case '>': /* DECPNM -- Normal keypad */
  1482. term.mode &= ~MODE_APPKEYPAD;
  1483. term.esc = 0;
  1484. break;
  1485. case '7': /* DECSC -- Save Cursor */
  1486. tcursor(CURSOR_SAVE);
  1487. term.esc = 0;
  1488. break;
  1489. case '8': /* DECRC -- Restore Cursor */
  1490. tcursor(CURSOR_LOAD);
  1491. term.esc = 0;
  1492. break;
  1493. case '\\': /* ST -- Stop */
  1494. term.esc = 0;
  1495. break;
  1496. default:
  1497. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1498. (uchar) ascii, isprint(ascii)?ascii:'.');
  1499. term.esc = 0;
  1500. }
  1501. }
  1502. } else {
  1503. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1504. sel.bx = -1;
  1505. switch(ascii) {
  1506. case '\t':
  1507. tputtab(1);
  1508. break;
  1509. case '\b':
  1510. tmoveto(term.c.x-1, term.c.y);
  1511. break;
  1512. case '\r':
  1513. tmoveto(0, term.c.y);
  1514. break;
  1515. case '\f':
  1516. case '\v':
  1517. case '\n':
  1518. /* go to first col if the mode is set */
  1519. tnewline(IS_SET(MODE_CRLF));
  1520. break;
  1521. case '\a':
  1522. if(!(xw.state & WIN_FOCUSED))
  1523. xseturgency(1);
  1524. break;
  1525. case '\033':
  1526. csireset();
  1527. term.esc = ESC_START;
  1528. break;
  1529. default:
  1530. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1531. tnewline(1); /* always go to first col */
  1532. tsetchar(c);
  1533. if(term.c.x+1 < term.col)
  1534. tmoveto(term.c.x+1, term.c.y);
  1535. else
  1536. term.c.state |= CURSOR_WRAPNEXT;
  1537. }
  1538. }
  1539. }
  1540. int
  1541. tresize(int col, int row) {
  1542. int i, x;
  1543. int minrow = MIN(row, term.row);
  1544. int mincol = MIN(col, term.col);
  1545. int slide = term.c.y - row + 1;
  1546. if(col < 1 || row < 1)
  1547. return 0;
  1548. /* free unneeded rows */
  1549. i = 0;
  1550. if(slide > 0) {
  1551. /* slide screen to keep cursor where we expect it -
  1552. * tscrollup would work here, but we can optimize to
  1553. * memmove because we're freeing the earlier lines */
  1554. for(/* i = 0 */; i < slide; i++) {
  1555. free(term.line[i]);
  1556. free(term.alt[i]);
  1557. }
  1558. memmove(term.line, term.line + slide, row * sizeof(Line));
  1559. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1560. }
  1561. for(i += row; i < term.row; i++) {
  1562. free(term.line[i]);
  1563. free(term.alt[i]);
  1564. }
  1565. /* resize to new height */
  1566. term.line = realloc(term.line, row * sizeof(Line));
  1567. term.alt = realloc(term.alt, row * sizeof(Line));
  1568. term.dirty = realloc(term.dirty, row * sizeof(*term.dirty));
  1569. term.tabs = realloc(term.tabs, col * sizeof(*term.tabs));
  1570. /* resize each row to new width, zero-pad if needed */
  1571. for(i = 0; i < minrow; i++) {
  1572. term.dirty[i] = 1;
  1573. term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
  1574. term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
  1575. for(x = mincol; x < col; x++) {
  1576. term.line[i][x].state = 0;
  1577. term.alt[i][x].state = 0;
  1578. }
  1579. }
  1580. /* allocate any new rows */
  1581. for(/* i == minrow */; i < row; i++) {
  1582. term.dirty[i] = 1;
  1583. term.line[i] = calloc(col, sizeof(Glyph));
  1584. term.alt [i] = calloc(col, sizeof(Glyph));
  1585. }
  1586. if(col > term.col) {
  1587. bool *bp = term.tabs + term.col;
  1588. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1589. while(--bp > term.tabs && !*bp)
  1590. /* nothing */ ;
  1591. for(bp += TAB; bp < term.tabs + col; bp += TAB)
  1592. *bp = 1;
  1593. }
  1594. /* update terminal size */
  1595. term.col = col, term.row = row;
  1596. /* make use of the LIMIT in tmoveto */
  1597. tmoveto(term.c.x, term.c.y);
  1598. /* reset scrolling region */
  1599. tsetscroll(0, row-1);
  1600. return (slide > 0);
  1601. }
  1602. void
  1603. xresize(int col, int row) {
  1604. xw.w = MAX(1, 2*BORDER + col * xw.cw);
  1605. xw.h = MAX(1, 2*BORDER + row * xw.ch);
  1606. }
  1607. void
  1608. xloadcols(void) {
  1609. int i, r, g, b;
  1610. XColor color;
  1611. ulong white = WhitePixel(xw.dpy, xw.scr);
  1612. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1613. for(i = 0; i < LEN(colorname); i++) {
  1614. if(!colorname[i])
  1615. continue;
  1616. if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
  1617. dc.col[i] = white;
  1618. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1619. } else
  1620. dc.col[i] = color.pixel;
  1621. }
  1622. /* load colors [16-255] ; same colors as xterm */
  1623. for(i = 16, r = 0; r < 6; r++)
  1624. for(g = 0; g < 6; g++)
  1625. for(b = 0; b < 6; b++) {
  1626. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1627. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1628. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1629. if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1630. dc.col[i] = white;
  1631. fprintf(stderr, "Could not allocate color %d\n", i);
  1632. } else
  1633. dc.col[i] = color.pixel;
  1634. i++;
  1635. }
  1636. for(r = 0; r < 24; r++, i++) {
  1637. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1638. if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1639. dc.col[i] = white;
  1640. fprintf(stderr, "Could not allocate color %d\n", i);
  1641. } else
  1642. dc.col[i] = color.pixel;
  1643. }
  1644. }
  1645. void
  1646. xclear(int x1, int y1, int x2, int y2) {
  1647. XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
  1648. XFillRectangle(xw.dpy, xw.buf, dc.gc,
  1649. BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
  1650. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1651. }
  1652. void
  1653. xhints(void) {
  1654. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1655. XWMHints wm = {.flags = InputHint, .input = 1};
  1656. XSizeHints *sizeh = NULL;
  1657. sizeh = XAllocSizeHints();
  1658. if(xw.isfixed == False) {
  1659. sizeh->flags = PSize | PResizeInc | PBaseSize;
  1660. sizeh->height = xw.h;
  1661. sizeh->width = xw.w;
  1662. sizeh->height_inc = xw.ch;
  1663. sizeh->width_inc = xw.cw;
  1664. sizeh->base_height = 2*BORDER;
  1665. sizeh->base_width = 2*BORDER;
  1666. } else {
  1667. sizeh->flags = PMaxSize | PMinSize;
  1668. sizeh->min_width = sizeh->max_width = xw.fw;
  1669. sizeh->min_height = sizeh->max_height = xw.fh;
  1670. }
  1671. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  1672. XFree(sizeh);
  1673. }
  1674. XFontSet
  1675. xinitfont(char *fontstr) {
  1676. XFontSet set;
  1677. char *def, **missing;
  1678. int n;
  1679. missing = NULL;
  1680. set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
  1681. if(missing) {
  1682. while(n--)
  1683. fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
  1684. XFreeStringList(missing);
  1685. }
  1686. return set;
  1687. }
  1688. void
  1689. xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
  1690. XFontStruct **xfonts;
  1691. char **font_names;
  1692. int i, n;
  1693. *ascent = *descent = *lbearing = *rbearing = 0;
  1694. n = XFontsOfFontSet(set, &xfonts, &font_names);
  1695. for(i = 0; i < n; i++) {
  1696. *ascent = MAX(*ascent, (*xfonts)->ascent);
  1697. *descent = MAX(*descent, (*xfonts)->descent);
  1698. *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
  1699. *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
  1700. xfonts++;
  1701. }
  1702. }
  1703. void
  1704. initfonts(char *fontstr, char *bfontstr) {
  1705. if((dc.font.set = xinitfont(fontstr)) == NULL ||
  1706. (dc.bfont.set = xinitfont(bfontstr)) == NULL)
  1707. die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
  1708. xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
  1709. &dc.font.lbearing, &dc.font.rbearing);
  1710. xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
  1711. &dc.bfont.lbearing, &dc.bfont.rbearing);
  1712. }
  1713. void
  1714. xinit(void) {
  1715. XSetWindowAttributes attrs;
  1716. Cursor cursor;
  1717. Window parent;
  1718. int sw, sh;
  1719. if(!(xw.dpy = XOpenDisplay(NULL)))
  1720. die("Can't open display\n");
  1721. xw.scr = XDefaultScreen(xw.dpy);
  1722. /* adjust fixed window geometry */
  1723. if(xw.isfixed) {
  1724. sw = DisplayWidth(xw.dpy, xw.scr);
  1725. sh = DisplayHeight(xw.dpy, xw.scr);
  1726. if(xw.fx < 0)
  1727. xw.fx = sw + xw.fx - xw.fw - 1;
  1728. if(xw.fy < 0)
  1729. xw.fy = sh + xw.fy - xw.fh - 1;
  1730. } else {
  1731. /* window - default size */
  1732. xw.h = 2*BORDER + term.row * xw.ch;
  1733. xw.w = 2*BORDER + term.col * xw.cw;
  1734. xw.fw = xw.w;
  1735. xw.fh = xw.h;
  1736. }
  1737. /* font */
  1738. initfonts(FONT, BOLDFONT);
  1739. /* XXX: Assuming same size for bold font */
  1740. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1741. xw.ch = dc.font.ascent + dc.font.descent;
  1742. /* colors */
  1743. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1744. xloadcols();
  1745. attrs.background_pixel = dc.col[DefaultBG];
  1746. attrs.border_pixel = dc.col[DefaultBG];
  1747. attrs.bit_gravity = NorthWestGravity;
  1748. attrs.event_mask = FocusChangeMask | KeyPressMask
  1749. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1750. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask
  1751. | EnterWindowMask | LeaveWindowMask;
  1752. attrs.colormap = xw.cmap;
  1753. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  1754. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  1755. xw.fw, xw.fh, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1756. XDefaultVisual(xw.dpy, xw.scr),
  1757. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1758. | CWColormap,
  1759. &attrs);
  1760. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  1761. /* input methods */
  1762. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1763. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1764. | XIMStatusNothing, XNClientWindow, xw.win,
  1765. XNFocusWindow, xw.win, NULL);
  1766. /* gc */
  1767. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1768. /* white cursor, black outline */
  1769. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1770. XDefineCursor(xw.dpy, xw.win, cursor);
  1771. XRecolorCursor(xw.dpy, cursor,
  1772. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1773. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1774. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1775. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1776. XMapWindow(xw.dpy, xw.win);
  1777. xhints();
  1778. XSync(xw.dpy, 0);
  1779. }
  1780. void
  1781. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1782. int fg = base.fg, bg = base.bg, temp;
  1783. int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1784. XFontSet fontset = dc.font.set;
  1785. int i;
  1786. /* only switch default fg/bg if term is in RV mode */
  1787. if(IS_SET(MODE_REVERSE)) {
  1788. if(fg == DefaultFG)
  1789. fg = DefaultBG;
  1790. if(bg == DefaultBG)
  1791. bg = DefaultFG;
  1792. }
  1793. if(base.mode & ATTR_REVERSE)
  1794. temp = fg, fg = bg, bg = temp;
  1795. if(base.mode & ATTR_BOLD) {
  1796. fg += 8;
  1797. fontset = dc.bfont.set;
  1798. }
  1799. XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
  1800. XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
  1801. if(base.mode & ATTR_GFX) {
  1802. for(i = 0; i < bytelen; i++) {
  1803. char c = gfx[(uint)s[i] % 256];
  1804. if(c)
  1805. s[i] = c;
  1806. else if(s[i] > 0x5f)
  1807. s[i] -= 0x5f;
  1808. }
  1809. }
  1810. XmbDrawImageString(xw.dpy, xw.buf, fontset, dc.gc, winx, winy, s, bytelen);
  1811. if(base.mode & ATTR_UNDERLINE)
  1812. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1813. }
  1814. /* copy buffer pixmap to screen pixmap */
  1815. void
  1816. xcopy() {
  1817. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  1818. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  1819. }
  1820. void
  1821. xdrawcursor(void) {
  1822. static int oldx = 0;
  1823. static int oldy = 0;
  1824. int sl;
  1825. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1826. LIMIT(oldx, 0, term.col-1);
  1827. LIMIT(oldy, 0, term.row-1);
  1828. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1829. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1830. /* remove the old cursor */
  1831. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1832. sl = utf8size(term.line[oldy][oldx].c);
  1833. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1834. } else
  1835. xclear(oldx, oldy, oldx, oldy);
  1836. xcopy(oldx, oldy, 1, 1);
  1837. /* draw the new one */
  1838. if(!(term.c.state & CURSOR_HIDE)) {
  1839. if(!(xw.state & WIN_FOCUSED))
  1840. g.bg = DefaultUCS;
  1841. if(IS_SET(MODE_REVERSE))
  1842. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  1843. sl = utf8size(g.c);
  1844. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1845. oldx = term.c.x, oldy = term.c.y;
  1846. }
  1847. xcopy(term.c.x, term.c.y, 1, 1);
  1848. }
  1849. void
  1850. redraw(void) {
  1851. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  1852. tfulldirt();
  1853. draw();
  1854. nanosleep(&tv, NULL);
  1855. }
  1856. void
  1857. draw() {
  1858. drawregion(0, 0, term.col, term.row);
  1859. xcopy();
  1860. gettimeofday(&xw.lastdraw, NULL);
  1861. }
  1862. void
  1863. drawregion(int x1, int y1, int x2, int y2) {
  1864. int ic, ib, x, y, ox, sl;
  1865. Glyph base, new;
  1866. char buf[DRAW_BUF_SIZ];
  1867. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
  1868. if((sel.alt && !alt) || (!sel.alt && alt))
  1869. ena_sel = 0;
  1870. if(!(xw.state & WIN_VISIBLE))
  1871. return;
  1872. for(y = y1; y < y2; y++) {
  1873. if(!term.dirty[y])
  1874. continue;
  1875. xclear(0, y, term.col, y);
  1876. term.dirty[y] = 0;
  1877. base = term.line[y][0];
  1878. ic = ib = ox = 0;
  1879. for(x = x1; x < x2; x++) {
  1880. new = term.line[y][x];
  1881. if(ena_sel && *(new.c) && selected(x, y))
  1882. new.mode ^= ATTR_REVERSE;
  1883. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1884. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1885. xdraws(buf, base, ox, y, ic, ib);
  1886. ic = ib = 0;
  1887. }
  1888. if(new.state & GLYPH_SET) {
  1889. if(ib == 0) {
  1890. ox = x;
  1891. base = new;
  1892. }
  1893. sl = utf8size(new.c);
  1894. memcpy(buf+ib, new.c, sl);
  1895. ib += sl;
  1896. ++ic;
  1897. }
  1898. }
  1899. if(ib > 0)
  1900. xdraws(buf, base, ox, y, ic, ib);
  1901. }
  1902. xdrawcursor();
  1903. }
  1904. void
  1905. expose(XEvent *ev) {
  1906. XExposeEvent *e = &ev->xexpose;
  1907. if(xw.state & WIN_REDRAW) {
  1908. if(!e->count)
  1909. xw.state &= ~WIN_REDRAW;
  1910. }
  1911. xcopy();
  1912. }
  1913. void
  1914. visibility(XEvent *ev) {
  1915. XVisibilityEvent *e = &ev->xvisibility;
  1916. if(e->state == VisibilityFullyObscured)
  1917. xw.state &= ~WIN_VISIBLE;
  1918. else if(!(xw.state & WIN_VISIBLE))
  1919. /* need a full redraw for next Expose, not just a buf copy */
  1920. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1921. }
  1922. void
  1923. unmap(XEvent *ev) {
  1924. xw.state &= ~WIN_VISIBLE;
  1925. }
  1926. void
  1927. xseturgency(int add) {
  1928. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1929. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1930. XSetWMHints(xw.dpy, xw.win, h);
  1931. XFree(h);
  1932. }
  1933. void
  1934. focus(XEvent *ev) {
  1935. if(ev->type == FocusIn) {
  1936. xw.state |= WIN_FOCUSED;
  1937. xseturgency(0);
  1938. } else
  1939. xw.state &= ~WIN_FOCUSED;
  1940. draw();
  1941. }
  1942. char*
  1943. kmap(KeySym k, uint state) {
  1944. int i;
  1945. state &= ~Mod2Mask;
  1946. for(i = 0; i < LEN(key); i++) {
  1947. uint mask = key[i].mask;
  1948. if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
  1949. return (char*)key[i].s;
  1950. }
  1951. return NULL;
  1952. }
  1953. void
  1954. kpress(XEvent *ev) {
  1955. XKeyEvent *e = &ev->xkey;
  1956. KeySym ksym;
  1957. char buf[32];
  1958. char *customkey;
  1959. int len;
  1960. int meta;
  1961. int shift;
  1962. Status status;
  1963. meta = e->state & Mod1Mask;
  1964. shift = e->state & ShiftMask;
  1965. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1966. /* 1. custom keys from config.h */
  1967. if((customkey = kmap(ksym, e->state)))
  1968. ttywrite(customkey, strlen(customkey));
  1969. /* 2. hardcoded (overrides X lookup) */
  1970. else
  1971. switch(ksym) {
  1972. case XK_Up:
  1973. case XK_Down:
  1974. case XK_Left:
  1975. case XK_Right:
  1976. /* XXX: shift up/down doesn't work */
  1977. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
  1978. ttywrite(buf, 3);
  1979. break;
  1980. case XK_Insert:
  1981. if(shift)
  1982. selpaste();
  1983. break;
  1984. case XK_Return:
  1985. if(IS_SET(MODE_CRLF))
  1986. ttywrite("\r\n", 2);
  1987. else
  1988. ttywrite("\r", 1);
  1989. break;
  1990. /* 3. X lookup */
  1991. default:
  1992. if(len > 0) {
  1993. if(meta && len == 1)
  1994. ttywrite("\033", 1);
  1995. ttywrite(buf, len);
  1996. }
  1997. break;
  1998. }
  1999. }
  2000. void
  2001. cmessage(XEvent *e) {
  2002. /* See xembed specs
  2003. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2004. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2005. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2006. xw.state |= WIN_FOCUSED;
  2007. xseturgency(0);
  2008. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2009. xw.state &= ~WIN_FOCUSED;
  2010. }
  2011. draw();
  2012. }
  2013. }
  2014. void
  2015. resize(XEvent *e) {
  2016. int col, row;
  2017. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2018. return;
  2019. xw.w = e->xconfigure.width;
  2020. xw.h = e->xconfigure.height;
  2021. col = (xw.w - 2*BORDER) / xw.cw;
  2022. row = (xw.h - 2*BORDER) / xw.ch;
  2023. if(col == term.col && row == term.row)
  2024. return;
  2025. if(tresize(col, row))
  2026. draw();
  2027. ttyresize(col, row);
  2028. xresize(col, row);
  2029. }
  2030. bool
  2031. last_draw_too_old(void) {
  2032. struct timeval now;
  2033. gettimeofday(&now, NULL);
  2034. return TIMEDIFF(now, xw.lastdraw) >= DRAW_TIMEOUT/1000;
  2035. }
  2036. void
  2037. run(void) {
  2038. XEvent ev;
  2039. fd_set rfd;
  2040. int xfd = XConnectionNumber(xw.dpy);
  2041. struct timeval timeout = {0};
  2042. bool stuff_to_print = 0;
  2043. for(;;) {
  2044. FD_ZERO(&rfd);
  2045. FD_SET(cmdfd, &rfd);
  2046. FD_SET(xfd, &rfd);
  2047. timeout.tv_sec = 0;
  2048. timeout.tv_usec = SELECT_TIMEOUT;
  2049. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, &timeout) < 0) {
  2050. if(errno == EINTR)
  2051. continue;
  2052. die("select failed: %s\n", SERRNO);
  2053. }
  2054. if(FD_ISSET(cmdfd, &rfd)) {
  2055. ttyread();
  2056. stuff_to_print = 1;
  2057. }
  2058. if(stuff_to_print && last_draw_too_old()) {
  2059. stuff_to_print = 0;
  2060. draw();
  2061. }
  2062. while(XPending(xw.dpy)) {
  2063. XNextEvent(xw.dpy, &ev);
  2064. if(XFilterEvent(&ev, xw.win))
  2065. continue;
  2066. if(handler[ev.type])
  2067. (handler[ev.type])(&ev);
  2068. }
  2069. }
  2070. }
  2071. int
  2072. main(int argc, char *argv[]) {
  2073. int i, bitm, xr, yr;
  2074. unsigned int wr, hr;
  2075. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2076. for(i = 1; i < argc; i++) {
  2077. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2078. case 't':
  2079. if(++i < argc) opt_title = argv[i];
  2080. break;
  2081. case 'c':
  2082. if(++i < argc) opt_class = argv[i];
  2083. break;
  2084. case 'w':
  2085. if(++i < argc) opt_embed = argv[i];
  2086. break;
  2087. case 'f':
  2088. if(++i < argc) opt_io = argv[i];
  2089. break;
  2090. case 'e':
  2091. /* eat every remaining arguments */
  2092. if(++i < argc) opt_cmd = &argv[i];
  2093. goto run;
  2094. case 'g':
  2095. if(++i >= argc)
  2096. break;
  2097. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2098. if(bitm & XValue)
  2099. xw.fx = xr;
  2100. if(bitm & YValue)
  2101. xw.fy = yr;
  2102. if(bitm & WidthValue)
  2103. xw.fw = (int)wr;
  2104. if(bitm & HeightValue)
  2105. xw.fh = (int)hr;
  2106. if(bitm & XNegative && xw.fx == 0)
  2107. xw.fx = -1;
  2108. if(bitm & XNegative && xw.fy == 0)
  2109. xw.fy = -1;
  2110. if(xw.fh != 0 && xw.fw != 0)
  2111. xw.isfixed = True;
  2112. break;
  2113. case 'v':
  2114. default:
  2115. die(USAGE);
  2116. }
  2117. }
  2118. run:
  2119. setlocale(LC_CTYPE, "");
  2120. tnew(80, 24);
  2121. ttynew();
  2122. xinit();
  2123. selinit();
  2124. run();
  2125. return 0;
  2126. }