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.

2408 lines
53 KiB

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