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.

1648 lines
36 KiB

14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
  1. /* See LICENSE for licence details. */
  2. #define _XOPEN_SOURCE 600
  3. #include <ctype.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <limits.h>
  7. #include <locale.h>
  8. #include <stdarg.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <signal.h>
  13. #include <sys/ioctl.h>
  14. #include <sys/select.h>
  15. #include <sys/stat.h>
  16. #include <sys/types.h>
  17. #include <sys/wait.h>
  18. #include <unistd.h>
  19. #include <X11/Xlib.h>
  20. #include <X11/Xatom.h>
  21. #include <X11/keysym.h>
  22. #include <X11/Xutil.h>
  23. #if defined(__linux)
  24. #include <pty.h>
  25. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  26. #include <util.h>
  27. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  28. #include <libutil.h>
  29. #endif
  30. #define USAGE \
  31. "st-" VERSION ", (c) 2010 st engineers\n" \
  32. "usage: st [-t title] [-e cmd] [-v]\n"
  33. /* Arbitrary sizes */
  34. #define ESC_TITLE_SIZ 256
  35. #define ESC_BUF_SIZ 256
  36. #define ESC_ARG_SIZ 16
  37. #define DRAW_BUF_SIZ 1024
  38. #define SERRNO strerror(errno)
  39. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  40. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  41. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  42. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  43. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  44. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  45. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  46. #define IS_SET(flag) (term.mode & (flag))
  47. /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
  48. enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
  49. enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT,
  50. CURSOR_SAVE, CURSOR_LOAD };
  51. enum { CURSOR_DEFAULT = 0, CURSOR_HIDE = 1, CURSOR_WRAPNEXT = 2 };
  52. enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
  53. enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4, MODE_ALTSCREEN=8 };
  54. enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
  55. enum { SCREEN_UPDATE, SCREEN_REDRAW };
  56. typedef struct {
  57. char c; /* character code */
  58. char mode; /* attribute flags */
  59. int fg; /* foreground */
  60. int bg; /* background */
  61. char state; /* state flags */
  62. } Glyph;
  63. typedef Glyph* Line;
  64. typedef struct {
  65. Glyph attr; /* current char attributes */
  66. int x;
  67. int y;
  68. char state;
  69. } TCursor;
  70. /* CSI Escape sequence structs */
  71. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  72. typedef struct {
  73. char buf[ESC_BUF_SIZ]; /* raw string */
  74. int len; /* raw string length */
  75. char priv;
  76. int arg[ESC_ARG_SIZ];
  77. int narg; /* nb of args */
  78. char mode;
  79. } CSIEscape;
  80. /* Internal representation of the screen */
  81. typedef struct {
  82. int row; /* nb row */
  83. int col; /* nb col */
  84. Line* line; /* screen */
  85. Line* alt; /* alternate screen */
  86. TCursor c; /* cursor */
  87. int top; /* top scroll limit */
  88. int bot; /* bottom scroll limit */
  89. int mode; /* terminal mode flags */
  90. int esc; /* escape state flags */
  91. char title[ESC_TITLE_SIZ];
  92. int titlelen;
  93. } Term;
  94. /* Purely graphic info */
  95. typedef struct {
  96. Display* dis;
  97. Colormap cmap;
  98. Window win;
  99. Pixmap buf;
  100. XIM xim;
  101. XIC xic;
  102. int scr;
  103. int w; /* window width */
  104. int h; /* window height */
  105. int bufw; /* pixmap width */
  106. int bufh; /* pixmap height */
  107. int ch; /* char height */
  108. int cw; /* char width */
  109. int focus;
  110. int vis; /* is visible */
  111. } XWindow;
  112. typedef struct {
  113. KeySym k;
  114. char s[ESC_BUF_SIZ];
  115. } Key;
  116. /* Drawing Context */
  117. typedef struct {
  118. unsigned long col[256];
  119. XFontStruct* font;
  120. XFontStruct* bfont;
  121. GC gc;
  122. } DC;
  123. /* TODO: use better name for vars... */
  124. typedef struct {
  125. int mode;
  126. int bx, by;
  127. int ex, ey;
  128. struct {int x, y;} b, e;
  129. char *clip;
  130. } Selection;
  131. #include "config.h"
  132. static void die(const char *errstr, ...);
  133. static void draw(int);
  134. static void execsh(void);
  135. static void sigchld(int);
  136. static void run(void);
  137. static void csidump(void);
  138. static void csihandle(void);
  139. static void csiparse(void);
  140. static void csireset(void);
  141. static void tclearregion(int, int, int, int);
  142. static void tcursor(int);
  143. static void tdeletechar(int);
  144. static void tdeleteline(int);
  145. static void tinsertblank(int);
  146. static void tinsertblankline(int);
  147. static void tmoveto(int, int);
  148. static void tnew(int, int);
  149. static void tnewline(void);
  150. static void tputtab(void);
  151. static void tputc(char);
  152. static void tputs(char*, int);
  153. static void treset(void);
  154. static void tresize(int, int);
  155. static void tscrollup(int, int);
  156. static void tscrolldown(int, int);
  157. static void tsetattr(int*, int);
  158. static void tsetchar(char);
  159. static void tsetscroll(int, int);
  160. static void tswapscreen(void);
  161. static void ttynew(void);
  162. static void ttyread(void);
  163. static void ttyresize(int, int);
  164. static void ttywrite(const char *, size_t);
  165. static void xdraws(char *, Glyph, int, int, int);
  166. static void xhints(void);
  167. static void xclear(int, int, int, int);
  168. static void xdrawcursor(void);
  169. static void xinit(void);
  170. static void xloadcols(void);
  171. static void xseturgency(int);
  172. static void expose(XEvent *);
  173. static void visibility(XEvent *);
  174. static void unmap(XEvent *);
  175. static char* kmap(KeySym);
  176. static void kpress(XEvent *);
  177. static void resize(XEvent *);
  178. static void focus(XEvent *);
  179. static void brelease(XEvent *);
  180. static void bpress(XEvent *);
  181. static void bmotion(XEvent *);
  182. static void selection_notify(XEvent *);
  183. static void selection_request(XEvent *);
  184. static void (*handler[LASTEvent])(XEvent *) = {
  185. [KeyPress] = kpress,
  186. [ConfigureNotify] = resize,
  187. [VisibilityNotify] = visibility,
  188. [UnmapNotify] = unmap,
  189. [Expose] = expose,
  190. [FocusIn] = focus,
  191. [FocusOut] = focus,
  192. [MotionNotify] = bmotion,
  193. [ButtonPress] = bpress,
  194. [ButtonRelease] = brelease,
  195. [SelectionNotify] = selection_notify,
  196. [SelectionRequest] = selection_request,
  197. };
  198. /* Globals */
  199. static DC dc;
  200. static XWindow xw;
  201. static Term term;
  202. static CSIEscape escseq;
  203. static int cmdfd;
  204. static pid_t pid;
  205. static Selection sel;
  206. static char *opt_cmd = NULL;
  207. static char *opt_title = NULL;
  208. void
  209. selinit(void) {
  210. sel.mode = 0;
  211. sel.bx = -1;
  212. sel.clip = NULL;
  213. }
  214. static inline int selected(int x, int y) {
  215. if(sel.ey == y && sel.by == y) {
  216. int bx = MIN(sel.bx, sel.ex);
  217. int ex = MAX(sel.bx, sel.ex);
  218. return BETWEEN(x, bx, ex);
  219. }
  220. return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
  221. || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
  222. }
  223. static void getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
  224. if(b)
  225. *b = e->xbutton.button;
  226. *x = e->xbutton.x/xw.cw;
  227. *y = e->xbutton.y/xw.ch;
  228. sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
  229. sel.b.y = MIN(sel.by, sel.ey);
  230. sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
  231. sel.e.y = MAX(sel.by, sel.ey);
  232. }
  233. static void bpress(XEvent *e) {
  234. sel.mode = 1;
  235. sel.ex = sel.bx = e->xbutton.x/xw.cw;
  236. sel.ey = sel.by = e->xbutton.y/xw.ch;
  237. }
  238. static char *getseltext() {
  239. char *str, *ptr;
  240. int ls, x, y, sz;
  241. if(sel.bx == -1)
  242. return NULL;
  243. sz = (term.col+1) * (sel.e.y-sel.b.y+1);
  244. ptr = str = malloc(sz);
  245. for(y = 0; y < term.row; y++) {
  246. for(x = 0; x < term.col; x++)
  247. if(term.line[y][x].state & GLYPH_SET && (ls = selected(x, y)))
  248. *ptr = term.line[y][x].c, ptr++;
  249. if(ls)
  250. *ptr = '\n', ptr++;
  251. }
  252. *ptr = 0;
  253. return str;
  254. }
  255. static void selection_notify(XEvent *e) {
  256. unsigned long nitems;
  257. unsigned long length;
  258. int format, res;
  259. unsigned char *data;
  260. Atom type;
  261. res = XGetWindowProperty(xw.dis, xw.win, XA_PRIMARY, 0, 0, False,
  262. AnyPropertyType, &type, &format, &nitems, &length, &data);
  263. switch(res) {
  264. case BadAtom:
  265. case BadValue:
  266. case BadWindow:
  267. fprintf(stderr, "Invalid paste, XGetWindowProperty0");
  268. return;
  269. }
  270. res = XGetWindowProperty(xw.dis, xw.win, XA_PRIMARY, 0, length, False,
  271. AnyPropertyType, &type, &format, &nitems, &length, &data);
  272. switch(res) {
  273. case BadAtom:
  274. case BadValue:
  275. case BadWindow:
  276. fprintf(stderr, "Invalid paste, XGetWindowProperty0");
  277. return;
  278. }
  279. if(data) {
  280. ttywrite((const char *) data, nitems * format / 8);
  281. XFree(data);
  282. }
  283. }
  284. static void selpaste() {
  285. XConvertSelection(xw.dis, XA_PRIMARY, XA_STRING, XA_PRIMARY, xw.win, CurrentTime);
  286. }
  287. static void selection_request(XEvent *e)
  288. {
  289. XSelectionRequestEvent *xsre;
  290. XSelectionEvent xev;
  291. int res;
  292. Atom xa_targets;
  293. xsre = (XSelectionRequestEvent *) e;
  294. xev.type = SelectionNotify;
  295. xev.requestor = xsre->requestor;
  296. xev.selection = xsre->selection;
  297. xev.target = xsre->target;
  298. xev.time = xsre->time;
  299. /* reject */
  300. xev.property = None;
  301. xa_targets = XInternAtom(xw.dis, "TARGETS", 0);
  302. if(xsre->target == xa_targets) {
  303. /* respond with the supported type */
  304. Atom string = XA_STRING;
  305. res = XChangeProperty(xsre->display, xsre->requestor, xsre->property, XA_ATOM, 32,
  306. PropModeReplace, (unsigned char *) &string, 1);
  307. switch(res) {
  308. case BadAlloc:
  309. case BadAtom:
  310. case BadMatch:
  311. case BadValue:
  312. case BadWindow:
  313. fprintf(stderr, "Error in selection_request, TARGETS");
  314. break;
  315. default:
  316. xev.property = xsre->property;
  317. }
  318. } else if(xsre->target == XA_STRING) {
  319. res = XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  320. xsre->target, 8, PropModeReplace, (unsigned char *) sel.clip,
  321. strlen(sel.clip));
  322. switch(res) {
  323. case BadAlloc:
  324. case BadAtom:
  325. case BadMatch:
  326. case BadValue:
  327. case BadWindow:
  328. fprintf(stderr, "Error in selection_request, XA_STRING");
  329. break;
  330. default:
  331. xev.property = xsre->property;
  332. }
  333. }
  334. /* all done, send a notification to the listener */
  335. res = XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev);
  336. switch(res) {
  337. case 0:
  338. case BadValue:
  339. case BadWindow:
  340. fprintf(stderr, "Error in selection_requested, XSendEvent");
  341. }
  342. }
  343. static void selcopy(char *str) {
  344. /* register the selection for both the clipboard and the primary */
  345. Atom clipboard;
  346. int res;
  347. free(sel.clip);
  348. sel.clip = str;
  349. res = XSetSelectionOwner(xw.dis, XA_PRIMARY, xw.win, CurrentTime);
  350. switch(res) {
  351. case BadAtom:
  352. case BadWindow:
  353. fprintf(stderr, "Invalid copy, XSetSelectionOwner");
  354. return;
  355. }
  356. clipboard = XInternAtom(xw.dis, "CLIPBOARD", 0);
  357. res = XSetSelectionOwner(xw.dis, clipboard, xw.win, CurrentTime);
  358. switch(res) {
  359. case BadAtom:
  360. case BadWindow:
  361. fprintf(stderr, "Invalid copy, XSetSelectionOwner");
  362. return;
  363. }
  364. XFlush(xw.dis);
  365. }
  366. /* TODO: doubleclick to select word */
  367. static void brelease(XEvent *e) {
  368. int b;
  369. sel.mode = 0;
  370. getbuttoninfo(e, &b, &sel.ex, &sel.ey);
  371. if(sel.bx==sel.ex && sel.by==sel.ey) {
  372. sel.bx = -1;
  373. if(b==2)
  374. selpaste();
  375. } else {
  376. if(b==1)
  377. selcopy(getseltext());
  378. }
  379. draw(1);
  380. }
  381. static void bmotion(XEvent *e) {
  382. if (sel.mode) {
  383. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  384. draw(1);
  385. }
  386. }
  387. #ifdef DEBUG
  388. void
  389. tdump(void) {
  390. int row, col;
  391. Glyph c;
  392. for(row = 0; row < term.row; row++) {
  393. for(col = 0; col < term.col; col++) {
  394. if(col == term.c.x && row == term.c.y)
  395. putchar('#');
  396. else {
  397. c = term.line[row][col];
  398. putchar(c.state & GLYPH_SET ? c.c : '.');
  399. }
  400. }
  401. putchar('\n');
  402. }
  403. }
  404. #endif
  405. void
  406. die(const char *errstr, ...) {
  407. va_list ap;
  408. va_start(ap, errstr);
  409. vfprintf(stderr, errstr, ap);
  410. va_end(ap);
  411. exit(EXIT_FAILURE);
  412. }
  413. void
  414. execsh(void) {
  415. char *args[] = {getenv("SHELL"), "-i", NULL};
  416. if(opt_cmd)
  417. args[0] = opt_cmd, args[1] = NULL;
  418. else
  419. DEFAULT(args[0], SHELL);
  420. putenv("TERM="TNAME);
  421. execvp(args[0], args);
  422. }
  423. void
  424. sigchld(int a) {
  425. int stat = 0;
  426. if(waitpid(pid, &stat, 0) < 0)
  427. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  428. if(WIFEXITED(stat))
  429. exit(WEXITSTATUS(stat));
  430. else
  431. exit(EXIT_FAILURE);
  432. }
  433. void
  434. ttynew(void) {
  435. int m, s;
  436. /* seems to work fine on linux, openbsd and freebsd */
  437. struct winsize w = {term.row, term.col, 0, 0};
  438. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  439. die("openpty failed: %s\n", SERRNO);
  440. switch(pid = fork()) {
  441. case -1:
  442. die("fork failed\n");
  443. break;
  444. case 0:
  445. setsid(); /* create a new process group */
  446. dup2(s, STDIN_FILENO);
  447. dup2(s, STDOUT_FILENO);
  448. dup2(s, STDERR_FILENO);
  449. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  450. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  451. close(s);
  452. close(m);
  453. execsh();
  454. break;
  455. default:
  456. close(s);
  457. cmdfd = m;
  458. signal(SIGCHLD, sigchld);
  459. }
  460. }
  461. void
  462. dump(char c) {
  463. static int col;
  464. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  465. if(++col % 10 == 0)
  466. fprintf(stderr, "\n");
  467. }
  468. void
  469. ttyread(void) {
  470. char buf[BUFSIZ];
  471. int ret;
  472. if((ret = read(cmdfd, buf, LEN(buf))) < 0)
  473. die("Couldn't read from shell: %s\n", SERRNO);
  474. else
  475. tputs(buf, ret);
  476. }
  477. void
  478. ttywrite(const char *s, size_t n) {
  479. if(write(cmdfd, s, n) == -1)
  480. die("write error on tty: %s\n", SERRNO);
  481. }
  482. void
  483. ttyresize(int x, int y) {
  484. struct winsize w;
  485. w.ws_row = term.row;
  486. w.ws_col = term.col;
  487. w.ws_xpixel = w.ws_ypixel = 0;
  488. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  489. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  490. }
  491. void
  492. tcursor(int mode) {
  493. static TCursor c;
  494. if(mode == CURSOR_SAVE)
  495. c = term.c;
  496. else if(mode == CURSOR_LOAD)
  497. term.c = c, tmoveto(c.x, c.y);
  498. }
  499. void
  500. treset(void) {
  501. term.c = (TCursor){{
  502. .mode = ATTR_NULL,
  503. .fg = DefaultFG,
  504. .bg = DefaultBG
  505. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  506. term.top = 0, term.bot = term.row - 1;
  507. term.mode = MODE_WRAP;
  508. tclearregion(0, 0, term.col-1, term.row-1);
  509. }
  510. void
  511. tnew(int col, int row) {
  512. /* set screen size */
  513. term.row = row, term.col = col;
  514. term.line = malloc(term.row * sizeof(Line));
  515. term.alt = malloc(term.row * sizeof(Line));
  516. for(row = 0 ; row < term.row; row++) {
  517. term.line[row] = malloc(term.col * sizeof(Glyph));
  518. term.alt [row] = malloc(term.col * sizeof(Glyph));
  519. }
  520. /* setup screen */
  521. treset();
  522. }
  523. void
  524. tswapscreen(void) {
  525. Line* tmp = term.line;
  526. term.line = term.alt;
  527. term.alt = tmp;
  528. term.mode ^= MODE_ALTSCREEN;
  529. }
  530. void
  531. tscrolldown(int orig, int n) {
  532. int i;
  533. Line temp;
  534. LIMIT(n, 0, term.bot-orig+1);
  535. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  536. for(i = term.bot; i >= orig+n; i--) {
  537. temp = term.line[i];
  538. term.line[i] = term.line[i-n];
  539. term.line[i-n] = temp;
  540. }
  541. }
  542. void
  543. tscrollup(int orig, int n) {
  544. int i;
  545. Line temp;
  546. LIMIT(n, 0, term.bot-orig+1);
  547. tclearregion(0, orig, term.col-1, orig+n-1);
  548. for(i = orig; i <= term.bot-n; i++) {
  549. temp = term.line[i];
  550. term.line[i] = term.line[i+n];
  551. term.line[i+n] = temp;
  552. }
  553. }
  554. void
  555. tnewline(void) {
  556. int y = term.c.y;
  557. if(term.c.y == term.bot)
  558. tscrollup(term.top, 1);
  559. else
  560. y++;
  561. tmoveto(0, y);
  562. }
  563. void
  564. csiparse(void) {
  565. /* int noarg = 1; */
  566. char *p = escseq.buf;
  567. escseq.narg = 0;
  568. if(*p == '?')
  569. escseq.priv = 1, p++;
  570. while(p < escseq.buf+escseq.len) {
  571. while(isdigit(*p)) {
  572. escseq.arg[escseq.narg] *= 10;
  573. escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
  574. }
  575. if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
  576. escseq.narg++, p++;
  577. else {
  578. escseq.mode = *p;
  579. escseq.narg++;
  580. return;
  581. }
  582. }
  583. }
  584. void
  585. tmoveto(int x, int y) {
  586. LIMIT(x, 0, term.col-1);
  587. LIMIT(y, 0, term.row-1);
  588. term.c.state &= ~CURSOR_WRAPNEXT;
  589. term.c.x = x;
  590. term.c.y = y;
  591. }
  592. void
  593. tsetchar(char c) {
  594. term.line[term.c.y][term.c.x] = term.c.attr;
  595. term.line[term.c.y][term.c.x].c = c;
  596. term.line[term.c.y][term.c.x].state |= GLYPH_SET;
  597. }
  598. void
  599. tclearregion(int x1, int y1, int x2, int y2) {
  600. int y, temp;
  601. if(x1 > x2)
  602. temp = x1, x1 = x2, x2 = temp;
  603. if(y1 > y2)
  604. temp = y1, y1 = y2, y2 = temp;
  605. LIMIT(x1, 0, term.col-1);
  606. LIMIT(x2, 0, term.col-1);
  607. LIMIT(y1, 0, term.row-1);
  608. LIMIT(y2, 0, term.row-1);
  609. for(y = y1; y <= y2; y++)
  610. memset(&term.line[y][x1], 0, sizeof(Glyph)*(x2-x1+1));
  611. }
  612. void
  613. tdeletechar(int n) {
  614. int src = term.c.x + n;
  615. int dst = term.c.x;
  616. int size = term.col - src;
  617. if(src >= term.col) {
  618. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  619. return;
  620. }
  621. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  622. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  623. }
  624. void
  625. tinsertblank(int n) {
  626. int src = term.c.x;
  627. int dst = src + n;
  628. int size = term.col - dst;
  629. if(dst >= term.col) {
  630. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  631. return;
  632. }
  633. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  634. tclearregion(src, term.c.y, dst - 1, term.c.y);
  635. }
  636. void
  637. tinsertblankline(int n) {
  638. if(term.c.y < term.top || term.c.y > term.bot)
  639. return;
  640. tscrolldown(term.c.y, n);
  641. }
  642. void
  643. tdeleteline(int n) {
  644. if(term.c.y < term.top || term.c.y > term.bot)
  645. return;
  646. tscrollup(term.c.y, n);
  647. }
  648. void
  649. tsetattr(int *attr, int l) {
  650. int i;
  651. for(i = 0; i < l; i++) {
  652. switch(attr[i]) {
  653. case 0:
  654. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
  655. term.c.attr.fg = DefaultFG;
  656. term.c.attr.bg = DefaultBG;
  657. break;
  658. case 1:
  659. term.c.attr.mode |= ATTR_BOLD;
  660. break;
  661. case 4:
  662. term.c.attr.mode |= ATTR_UNDERLINE;
  663. break;
  664. case 7:
  665. term.c.attr.mode |= ATTR_REVERSE;
  666. break;
  667. case 22:
  668. term.c.attr.mode &= ~ATTR_BOLD;
  669. break;
  670. case 24:
  671. term.c.attr.mode &= ~ATTR_UNDERLINE;
  672. break;
  673. case 27:
  674. term.c.attr.mode &= ~ATTR_REVERSE;
  675. break;
  676. case 38:
  677. if (i + 2 < l && attr[i + 1] == 5) {
  678. i += 2;
  679. if (BETWEEN(attr[i], 0, 255))
  680. term.c.attr.fg = attr[i];
  681. else
  682. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
  683. }
  684. else
  685. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
  686. break;
  687. case 39:
  688. term.c.attr.fg = DefaultFG;
  689. break;
  690. case 48:
  691. if (i + 2 < l && attr[i + 1] == 5) {
  692. i += 2;
  693. if (BETWEEN(attr[i], 0, 255))
  694. term.c.attr.bg = attr[i];
  695. else
  696. fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
  697. }
  698. else
  699. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
  700. break;
  701. case 49:
  702. term.c.attr.bg = DefaultBG;
  703. break;
  704. default:
  705. if(BETWEEN(attr[i], 30, 37))
  706. term.c.attr.fg = attr[i] - 30;
  707. else if(BETWEEN(attr[i], 40, 47))
  708. term.c.attr.bg = attr[i] - 40;
  709. else if(BETWEEN(attr[i], 90, 97))
  710. term.c.attr.fg = attr[i] - 90 + 8;
  711. else if(BETWEEN(attr[i], 100, 107))
  712. term.c.attr.fg = attr[i] - 100 + 8;
  713. else
  714. fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
  715. break;
  716. }
  717. }
  718. }
  719. void
  720. tsetscroll(int t, int b) {
  721. int temp;
  722. LIMIT(t, 0, term.row-1);
  723. LIMIT(b, 0, term.row-1);
  724. if(t > b) {
  725. temp = t;
  726. t = b;
  727. b = temp;
  728. }
  729. term.top = t;
  730. term.bot = b;
  731. }
  732. void
  733. csihandle(void) {
  734. switch(escseq.mode) {
  735. default:
  736. unknown:
  737. printf("erresc: unknown csi ");
  738. csidump();
  739. /* die(""); */
  740. break;
  741. case '@': /* ICH -- Insert <n> blank char */
  742. DEFAULT(escseq.arg[0], 1);
  743. tinsertblank(escseq.arg[0]);
  744. break;
  745. case 'A': /* CUU -- Cursor <n> Up */
  746. case 'e':
  747. DEFAULT(escseq.arg[0], 1);
  748. tmoveto(term.c.x, term.c.y-escseq.arg[0]);
  749. break;
  750. case 'B': /* CUD -- Cursor <n> Down */
  751. DEFAULT(escseq.arg[0], 1);
  752. tmoveto(term.c.x, term.c.y+escseq.arg[0]);
  753. break;
  754. case 'C': /* CUF -- Cursor <n> Forward */
  755. case 'a':
  756. DEFAULT(escseq.arg[0], 1);
  757. tmoveto(term.c.x+escseq.arg[0], term.c.y);
  758. break;
  759. case 'D': /* CUB -- Cursor <n> Backward */
  760. DEFAULT(escseq.arg[0], 1);
  761. tmoveto(term.c.x-escseq.arg[0], term.c.y);
  762. break;
  763. case 'E': /* CNL -- Cursor <n> Down and first col */
  764. DEFAULT(escseq.arg[0], 1);
  765. tmoveto(0, term.c.y+escseq.arg[0]);
  766. break;
  767. case 'F': /* CPL -- Cursor <n> Up and first col */
  768. DEFAULT(escseq.arg[0], 1);
  769. tmoveto(0, term.c.y-escseq.arg[0]);
  770. break;
  771. case 'G': /* CHA -- Move to <col> */
  772. case '`': /* XXX: HPA -- same? */
  773. DEFAULT(escseq.arg[0], 1);
  774. tmoveto(escseq.arg[0]-1, term.c.y);
  775. break;
  776. case 'H': /* CUP -- Move to <row> <col> */
  777. case 'f': /* XXX: HVP -- same? */
  778. DEFAULT(escseq.arg[0], 1);
  779. DEFAULT(escseq.arg[1], 1);
  780. tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
  781. break;
  782. /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
  783. case 'J': /* ED -- Clear screen */
  784. switch(escseq.arg[0]) {
  785. case 0: /* below */
  786. tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
  787. break;
  788. case 1: /* above */
  789. tclearregion(0, 0, term.c.x, term.c.y);
  790. break;
  791. case 2: /* all */
  792. tclearregion(0, 0, term.col-1, term.row-1);
  793. break;
  794. default:
  795. goto unknown;
  796. }
  797. break;
  798. case 'K': /* EL -- Clear line */
  799. switch(escseq.arg[0]) {
  800. case 0: /* right */
  801. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  802. break;
  803. case 1: /* left */
  804. tclearregion(0, term.c.y, term.c.x, term.c.y);
  805. break;
  806. case 2: /* all */
  807. tclearregion(0, term.c.y, term.col-1, term.c.y);
  808. break;
  809. }
  810. break;
  811. case 'S': /* SU -- Scroll <n> line up */
  812. DEFAULT(escseq.arg[0], 1);
  813. tscrollup(term.top, escseq.arg[0]);
  814. break;
  815. case 'T': /* SD -- Scroll <n> line down */
  816. DEFAULT(escseq.arg[0], 1);
  817. tscrolldown(term.top, escseq.arg[0]);
  818. break;
  819. case 'L': /* IL -- Insert <n> blank lines */
  820. DEFAULT(escseq.arg[0], 1);
  821. tinsertblankline(escseq.arg[0]);
  822. break;
  823. case 'l': /* RM -- Reset Mode */
  824. if(escseq.priv) {
  825. switch(escseq.arg[0]) {
  826. case 1:
  827. term.mode &= ~MODE_APPKEYPAD;
  828. break;
  829. case 5: /* TODO: DECSCNM -- Remove reverse video */
  830. break;
  831. case 7:
  832. term.mode &= ~MODE_WRAP;
  833. break;
  834. case 12: /* att610 -- Stop blinking cursor (IGNORED) */
  835. break;
  836. case 25:
  837. term.c.state |= CURSOR_HIDE;
  838. break;
  839. case 1049: /* = 1047 and 1048 */
  840. case 1047:
  841. if(IS_SET(MODE_ALTSCREEN)) {
  842. tclearregion(0, 0, term.col-1, term.row-1);
  843. tswapscreen();
  844. }
  845. if(escseq.arg[0] == 1047)
  846. break;
  847. case 1048:
  848. tcursor(CURSOR_LOAD);
  849. break;
  850. default:
  851. goto unknown;
  852. }
  853. } else {
  854. switch(escseq.arg[0]) {
  855. case 4:
  856. term.mode &= ~MODE_INSERT;
  857. break;
  858. default:
  859. goto unknown;
  860. }
  861. }
  862. break;
  863. case 'M': /* DL -- Delete <n> lines */
  864. DEFAULT(escseq.arg[0], 1);
  865. tdeleteline(escseq.arg[0]);
  866. break;
  867. case 'X': /* ECH -- Erase <n> char */
  868. DEFAULT(escseq.arg[0], 1);
  869. tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
  870. break;
  871. case 'P': /* DCH -- Delete <n> char */
  872. DEFAULT(escseq.arg[0], 1);
  873. tdeletechar(escseq.arg[0]);
  874. break;
  875. /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
  876. case 'd': /* VPA -- Move to <row> */
  877. DEFAULT(escseq.arg[0], 1);
  878. tmoveto(term.c.x, escseq.arg[0]-1);
  879. break;
  880. case 'h': /* SM -- Set terminal mode */
  881. if(escseq.priv) {
  882. switch(escseq.arg[0]) {
  883. case 1:
  884. term.mode |= MODE_APPKEYPAD;
  885. break;
  886. case 5: /* DECSCNM -- Reverve video */
  887. /* TODO: set REVERSE on the whole screen (f) */
  888. break;
  889. case 7:
  890. term.mode |= MODE_WRAP;
  891. break;
  892. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  893. /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
  894. if(escseq.narg > 1 && escseq.arg[1] != 25)
  895. break;
  896. case 25:
  897. term.c.state &= ~CURSOR_HIDE;
  898. break;
  899. case 1049: /* = 1047 and 1048 */
  900. case 1047:
  901. if(IS_SET(MODE_ALTSCREEN))
  902. tclearregion(0, 0, term.col-1, term.row-1);
  903. else
  904. tswapscreen();
  905. if(escseq.arg[0] == 1047)
  906. break;
  907. case 1048:
  908. tcursor(CURSOR_SAVE);
  909. break;
  910. default: goto unknown;
  911. }
  912. } else {
  913. switch(escseq.arg[0]) {
  914. case 4:
  915. term.mode |= MODE_INSERT;
  916. break;
  917. default: goto unknown;
  918. }
  919. };
  920. break;
  921. case 'm': /* SGR -- Terminal attribute (color) */
  922. tsetattr(escseq.arg, escseq.narg);
  923. break;
  924. case 'r': /* DECSTBM -- Set Scrolling Region */
  925. if(escseq.priv)
  926. goto unknown;
  927. else {
  928. DEFAULT(escseq.arg[0], 1);
  929. DEFAULT(escseq.arg[1], term.row);
  930. tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
  931. tmoveto(0, 0);
  932. }
  933. break;
  934. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  935. tcursor(CURSOR_SAVE);
  936. break;
  937. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  938. tcursor(CURSOR_LOAD);
  939. break;
  940. }
  941. }
  942. void
  943. csidump(void) {
  944. int i;
  945. printf("ESC [ %s", escseq.priv ? "? " : "");
  946. if(escseq.narg)
  947. for(i = 0; i < escseq.narg; i++)
  948. printf("%d ", escseq.arg[i]);
  949. if(escseq.mode)
  950. putchar(escseq.mode);
  951. putchar('\n');
  952. }
  953. void
  954. csireset(void) {
  955. memset(&escseq, 0, sizeof(escseq));
  956. }
  957. void
  958. tputtab(void) {
  959. int space = TAB - term.c.x % TAB;
  960. tmoveto(term.c.x + space, term.c.y);
  961. }
  962. void
  963. tputc(char c) {
  964. if(term.esc & ESC_START) {
  965. if(term.esc & ESC_CSI) {
  966. escseq.buf[escseq.len++] = c;
  967. if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
  968. term.esc = 0;
  969. csiparse(), csihandle();
  970. }
  971. /* TODO: handle other OSC */
  972. } else if(term.esc & ESC_OSC) {
  973. if(c == ';') {
  974. term.titlelen = 0;
  975. term.esc = ESC_START | ESC_TITLE;
  976. }
  977. } else if(term.esc & ESC_TITLE) {
  978. if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
  979. term.esc = 0;
  980. term.title[term.titlelen] = '\0';
  981. XStoreName(xw.dis, xw.win, term.title);
  982. } else {
  983. term.title[term.titlelen++] = c;
  984. }
  985. } else if(term.esc & ESC_ALTCHARSET) {
  986. switch(c) {
  987. case '0': /* Line drawing crap */
  988. term.c.attr.mode |= ATTR_GFX;
  989. break;
  990. case 'B': /* Back to regular text */
  991. term.c.attr.mode &= ~ATTR_GFX;
  992. break;
  993. default:
  994. printf("esc unhandled charset: ESC ( %c\n", c);
  995. }
  996. term.esc = 0;
  997. } else {
  998. switch(c) {
  999. case '[':
  1000. term.esc |= ESC_CSI;
  1001. break;
  1002. case ']':
  1003. term.esc |= ESC_OSC;
  1004. break;
  1005. case '(':
  1006. term.esc |= ESC_ALTCHARSET;
  1007. break;
  1008. case 'D': /* IND -- Linefeed */
  1009. if(term.c.y == term.bot)
  1010. tscrollup(term.top, 1);
  1011. else
  1012. tmoveto(term.c.x, term.c.y+1);
  1013. term.esc = 0;
  1014. break;
  1015. case 'E': /* NEL -- Next line */
  1016. tnewline();
  1017. term.esc = 0;
  1018. break;
  1019. case 'M': /* RI -- Reverse index */
  1020. if(term.c.y == term.top)
  1021. tscrolldown(term.top, 1);
  1022. else
  1023. tmoveto(term.c.x, term.c.y-1);
  1024. term.esc = 0;
  1025. break;
  1026. case 'c': /* RIS -- Reset to inital state */
  1027. treset();
  1028. term.esc = 0;
  1029. break;
  1030. case '=': /* DECPAM -- Application keypad */
  1031. term.mode |= MODE_APPKEYPAD;
  1032. term.esc = 0;
  1033. break;
  1034. case '>': /* DECPNM -- Normal keypad */
  1035. term.mode &= ~MODE_APPKEYPAD;
  1036. term.esc = 0;
  1037. break;
  1038. case '7': /* DECSC -- Save Cursor */
  1039. tcursor(CURSOR_SAVE);
  1040. term.esc = 0;
  1041. break;
  1042. case '8': /* DECRC -- Restore Cursor */
  1043. tcursor(CURSOR_LOAD);
  1044. term.esc = 0;
  1045. break;
  1046. default:
  1047. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
  1048. term.esc = 0;
  1049. }
  1050. }
  1051. } else {
  1052. switch(c) {
  1053. case '\t':
  1054. tputtab();
  1055. break;
  1056. case '\b':
  1057. tmoveto(term.c.x-1, term.c.y);
  1058. break;
  1059. case '\r':
  1060. tmoveto(0, term.c.y);
  1061. break;
  1062. case '\n':
  1063. tnewline();
  1064. break;
  1065. case '\a':
  1066. if(!xw.focus)
  1067. xseturgency(1);
  1068. break;
  1069. case '\033':
  1070. csireset();
  1071. term.esc = ESC_START;
  1072. break;
  1073. default:
  1074. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1075. tnewline();
  1076. tsetchar(c);
  1077. if(term.c.x+1 < term.col)
  1078. tmoveto(term.c.x+1, term.c.y);
  1079. else
  1080. term.c.state |= CURSOR_WRAPNEXT;
  1081. break;
  1082. }
  1083. }
  1084. }
  1085. void
  1086. tputs(char *s, int len) {
  1087. for(; len > 0; len--)
  1088. tputc(*s++);
  1089. }
  1090. void
  1091. tresize(int col, int row) {
  1092. int i;
  1093. int minrow = MIN(row, term.row);
  1094. int mincol = MIN(col, term.col);
  1095. int slide = term.c.y - row + 1;
  1096. if(col < 1 || row < 1)
  1097. return;
  1098. /* free unneeded rows */
  1099. i = 0;
  1100. if(slide > 0) {
  1101. /* slide screen to keep cursor where we expect it -
  1102. * tscrollup would work here, but we can optimize to
  1103. * memmove because we're freeing the earlier lines */
  1104. for(/* i = 0 */; i < slide; i++) {
  1105. free(term.line[i]);
  1106. free(term.alt[i]);
  1107. }
  1108. memmove(term.line, term.line + slide, row * sizeof(Line));
  1109. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1110. }
  1111. for(i += row; i < term.row; i++) {
  1112. free(term.line[i]);
  1113. free(term.alt[i]);
  1114. }
  1115. /* resize to new height */
  1116. term.line = realloc(term.line, row * sizeof(Line));
  1117. term.alt = realloc(term.alt, row * sizeof(Line));
  1118. /* resize each row to new width, zero-pad if needed */
  1119. for(i = 0; i < minrow; i++) {
  1120. term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
  1121. term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
  1122. memset(term.line[i] + mincol, 0, (col - mincol) * sizeof(Glyph));
  1123. memset(term.alt[i] + mincol, 0, (col - mincol) * sizeof(Glyph));
  1124. }
  1125. /* allocate any new rows */
  1126. for(/* i == minrow */; i < row; i++) {
  1127. term.line[i] = calloc(col, sizeof(Glyph));
  1128. term.alt [i] = calloc(col, sizeof(Glyph));
  1129. }
  1130. /* update terminal size */
  1131. term.col = col, term.row = row;
  1132. /* make use of the LIMIT in tmoveto */
  1133. tmoveto(term.c.x, term.c.y);
  1134. /* reset scrolling region */
  1135. tsetscroll(0, row-1);
  1136. }
  1137. void
  1138. xloadcols(void) {
  1139. int i, r, g, b;
  1140. XColor color;
  1141. unsigned long white = WhitePixel(xw.dis, xw.scr);
  1142. for(i = 0; i < 16; i++) {
  1143. if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
  1144. dc.col[i] = white;
  1145. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1146. } else
  1147. dc.col[i] = color.pixel;
  1148. }
  1149. /* same colors as xterm */
  1150. for(r = 0; r < 6; r++)
  1151. for(g = 0; g < 6; g++)
  1152. for(b = 0; b < 6; b++) {
  1153. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1154. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1155. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1156. if (!XAllocColor(xw.dis, xw.cmap, &color)) {
  1157. dc.col[i] = white;
  1158. fprintf(stderr, "Could not allocate color %d\n", i);
  1159. } else
  1160. dc.col[i] = color.pixel;
  1161. i++;
  1162. }
  1163. for(r = 0; r < 24; r++, i++) {
  1164. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1165. if (!XAllocColor(xw.dis, xw.cmap, &color)) {
  1166. dc.col[i] = white;
  1167. fprintf(stderr, "Could not allocate color %d\n", i);
  1168. } else
  1169. dc.col[i] = color.pixel;
  1170. }
  1171. }
  1172. void
  1173. xclear(int x1, int y1, int x2, int y2) {
  1174. XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
  1175. XFillRectangle(xw.dis, xw.buf, dc.gc,
  1176. x1 * xw.cw, y1 * xw.ch,
  1177. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1178. }
  1179. void
  1180. xhints(void)
  1181. {
  1182. XClassHint class = {TNAME, TNAME};
  1183. XWMHints wm = {.flags = InputHint, .input = 1};
  1184. XSizeHints size = {
  1185. .flags = PSize | PResizeInc | PBaseSize,
  1186. .height = xw.h,
  1187. .width = xw.w,
  1188. .height_inc = xw.ch,
  1189. .width_inc = xw.cw,
  1190. .base_height = 2*BORDER,
  1191. .base_width = 2*BORDER,
  1192. };
  1193. XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
  1194. }
  1195. void
  1196. xinit(void) {
  1197. XSetWindowAttributes attrs;
  1198. if(!(xw.dis = XOpenDisplay(NULL)))
  1199. die("Can't open display\n");
  1200. xw.scr = XDefaultScreen(xw.dis);
  1201. /* font */
  1202. if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
  1203. die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
  1204. /* XXX: Assuming same size for bold font */
  1205. xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
  1206. xw.ch = dc.font->ascent + dc.font->descent;
  1207. /* colors */
  1208. xw.cmap = XDefaultColormap(xw.dis, xw.scr);
  1209. xloadcols();
  1210. /* window - default size */
  1211. xw.bufh = 24 * xw.ch;
  1212. xw.bufw = 80 * xw.cw;
  1213. xw.h = xw.bufh + 2*BORDER;
  1214. xw.w = xw.bufw + 2*BORDER;
  1215. attrs.background_pixel = dc.col[DefaultBG];
  1216. attrs.border_pixel = dc.col[DefaultBG];
  1217. attrs.bit_gravity = NorthWestGravity;
  1218. attrs.event_mask = FocusChangeMask | KeyPressMask
  1219. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1220. | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
  1221. attrs.colormap = xw.cmap;
  1222. xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
  1223. xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
  1224. XDefaultVisual(xw.dis, xw.scr),
  1225. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1226. | CWColormap,
  1227. &attrs);
  1228. xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
  1229. /* input methods */
  1230. xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
  1231. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1232. | XIMStatusNothing, XNClientWindow, xw.win,
  1233. XNFocusWindow, xw.win, NULL);
  1234. /* gc */
  1235. dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
  1236. XMapWindow(xw.dis, xw.win);
  1237. xhints();
  1238. XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
  1239. XSync(xw.dis, 0);
  1240. }
  1241. void
  1242. xdraws(char *s, Glyph base, int x, int y, int len) {
  1243. unsigned long xfg, xbg;
  1244. int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
  1245. int i;
  1246. if(base.mode & ATTR_REVERSE)
  1247. xfg = dc.col[base.bg], xbg = dc.col[base.fg];
  1248. else
  1249. xfg = dc.col[base.fg], xbg = dc.col[base.bg];
  1250. XSetBackground(xw.dis, dc.gc, xbg);
  1251. XSetForeground(xw.dis, dc.gc, xfg);
  1252. if(base.mode & ATTR_GFX)
  1253. for(i = 0; i < len; i++) {
  1254. char c = gfx[(unsigned int)s[i] % 256];
  1255. if(c)
  1256. s[i] = c;
  1257. else if(s[i] > 0x5f)
  1258. s[i] -= 0x5f;
  1259. }
  1260. XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
  1261. XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
  1262. if(base.mode & ATTR_UNDERLINE)
  1263. XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1264. }
  1265. void
  1266. xdrawcursor(void) {
  1267. static int oldx = 0;
  1268. static int oldy = 0;
  1269. Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
  1270. LIMIT(oldx, 0, term.col-1);
  1271. LIMIT(oldy, 0, term.row-1);
  1272. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1273. g.c = term.line[term.c.y][term.c.x].c;
  1274. /* remove the old cursor */
  1275. if(term.line[oldy][oldx].state & GLYPH_SET)
  1276. xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
  1277. else
  1278. xclear(oldx, oldy, oldx, oldy);
  1279. /* draw the new one */
  1280. if(!(term.c.state & CURSOR_HIDE) && xw.focus) {
  1281. xdraws(&g.c, g, term.c.x, term.c.y, 1);
  1282. oldx = term.c.x, oldy = term.c.y;
  1283. }
  1284. }
  1285. #ifdef DEBUG
  1286. /* basic drawing routines */
  1287. void
  1288. xdrawc(int x, int y, Glyph g) {
  1289. XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
  1290. XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
  1291. XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
  1292. XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
  1293. XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
  1294. }
  1295. void
  1296. draw(int dummy) {
  1297. int x, y;
  1298. xclear(0, 0, term.col-1, term.row-1);
  1299. for(y = 0; y < term.row; y++)
  1300. for(x = 0; x < term.col; x++)
  1301. if(term.line[y][x].state & GLYPH_SET)
  1302. xdrawc(x, y, term.line[y][x]);
  1303. xdrawcursor();
  1304. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1305. XFlush(xw.dis);
  1306. }
  1307. #else
  1308. /* optimized drawing routine */
  1309. void
  1310. draw(int redraw_all) {
  1311. int i, x, y, ox;
  1312. Glyph base, new;
  1313. char buf[DRAW_BUF_SIZ];
  1314. if(!xw.vis)
  1315. return;
  1316. xclear(0, 0, term.col-1, term.row-1);
  1317. for(y = 0; y < term.row; y++) {
  1318. base = term.line[y][0];
  1319. i = ox = 0;
  1320. for(x = 0; x < term.col; x++) {
  1321. new = term.line[y][x];
  1322. if(sel.bx!=-1 && new.c && selected(x, y))
  1323. new.mode ^= ATTR_REVERSE;
  1324. if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1325. i >= DRAW_BUF_SIZ)) {
  1326. xdraws(buf, base, ox, y, i);
  1327. i = 0;
  1328. }
  1329. if(new.state & GLYPH_SET) {
  1330. if(i == 0) {
  1331. ox = x;
  1332. base = new;
  1333. }
  1334. buf[i++] = new.c;
  1335. }
  1336. }
  1337. if(i > 0)
  1338. xdraws(buf, base, ox, y, i);
  1339. }
  1340. xdrawcursor();
  1341. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1342. XFlush(xw.dis);
  1343. }
  1344. #endif
  1345. void
  1346. expose(XEvent *ev) {
  1347. draw(SCREEN_REDRAW);
  1348. }
  1349. void
  1350. visibility(XEvent *ev) {
  1351. XVisibilityEvent *e = &ev->xvisibility;
  1352. /* XXX if this goes from 0 to 1, need a full redraw for next Expose,
  1353. * not just a buf copy */
  1354. xw.vis = e->state != VisibilityFullyObscured;
  1355. }
  1356. void
  1357. unmap(XEvent *ev) {
  1358. xw.vis = 0;
  1359. }
  1360. void
  1361. xseturgency(int add) {
  1362. XWMHints *h = XGetWMHints(xw.dis, xw.win);
  1363. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1364. XSetWMHints(xw.dis, xw.win, h);
  1365. XFree(h);
  1366. }
  1367. void
  1368. focus(XEvent *ev) {
  1369. if((xw.focus = ev->type == FocusIn))
  1370. xseturgency(0);
  1371. draw(SCREEN_UPDATE);
  1372. }
  1373. char*
  1374. kmap(KeySym k) {
  1375. int i;
  1376. for(i = 0; i < LEN(key); i++)
  1377. if(key[i].k == k)
  1378. return (char*)key[i].s;
  1379. return NULL;
  1380. }
  1381. void
  1382. kpress(XEvent *ev) {
  1383. XKeyEvent *e = &ev->xkey;
  1384. KeySym ksym;
  1385. char buf[32];
  1386. char *customkey;
  1387. int len;
  1388. int meta;
  1389. int shift;
  1390. Status status;
  1391. meta = e->state & Mod1Mask;
  1392. shift = e->state & ShiftMask;
  1393. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1394. if((customkey = kmap(ksym)))
  1395. ttywrite(customkey, strlen(customkey));
  1396. else if(len > 0) {
  1397. buf[sizeof(buf)-1] = '\0';
  1398. if(meta && len == 1)
  1399. ttywrite("\033", 1);
  1400. ttywrite(buf, len);
  1401. } else
  1402. switch(ksym) {
  1403. case XK_Up:
  1404. case XK_Down:
  1405. case XK_Left:
  1406. case XK_Right:
  1407. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
  1408. ttywrite(buf, 3);
  1409. break;
  1410. case XK_Insert:
  1411. if(shift)
  1412. selpaste(), draw(1);
  1413. break;
  1414. default:
  1415. fprintf(stderr, "errkey: %d\n", (int)ksym);
  1416. break;
  1417. }
  1418. }
  1419. void
  1420. resize(XEvent *e) {
  1421. int col, row;
  1422. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  1423. return;
  1424. xw.w = e->xconfigure.width;
  1425. xw.h = e->xconfigure.height;
  1426. xw.bufw = xw.w - 2*BORDER;
  1427. xw.bufh = xw.h - 2*BORDER;
  1428. col = xw.bufw / xw.cw;
  1429. row = xw.bufh / xw.ch;
  1430. tresize(col, row);
  1431. ttyresize(col, row);
  1432. xw.bufh = MAX(1, xw.bufh);
  1433. xw.bufw = MAX(1, xw.bufw);
  1434. XFreePixmap(xw.dis, xw.buf);
  1435. xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
  1436. }
  1437. void
  1438. run(void) {
  1439. XEvent ev;
  1440. fd_set rfd;
  1441. int xfd = XConnectionNumber(xw.dis);
  1442. for(;;) {
  1443. FD_ZERO(&rfd);
  1444. FD_SET(cmdfd, &rfd);
  1445. FD_SET(xfd, &rfd);
  1446. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
  1447. if(errno == EINTR)
  1448. continue;
  1449. die("select failed: %s\n", SERRNO);
  1450. }
  1451. if(FD_ISSET(cmdfd, &rfd)) {
  1452. ttyread();
  1453. draw(SCREEN_UPDATE);
  1454. }
  1455. while(XPending(xw.dis)) {
  1456. XNextEvent(xw.dis, &ev);
  1457. if (XFilterEvent(&ev, xw.win))
  1458. continue;
  1459. if(handler[ev.type])
  1460. (handler[ev.type])(&ev);
  1461. }
  1462. }
  1463. }
  1464. int
  1465. main(int argc, char *argv[]) {
  1466. int i;
  1467. for(i = 1; i < argc; i++) {
  1468. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  1469. case 't':
  1470. if(++i < argc) opt_title = argv[i];
  1471. break;
  1472. case 'e':
  1473. if(++i < argc) opt_cmd = argv[i];
  1474. break;
  1475. case 'v':
  1476. default:
  1477. die(USAGE);
  1478. }
  1479. }
  1480. setlocale(LC_CTYPE, "");
  1481. tnew(80, 24);
  1482. ttynew();
  1483. xinit();
  1484. selinit();
  1485. run();
  1486. return 0;
  1487. }