My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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