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.

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