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.

1683 lines
38 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
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. 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 '\f':
  1071. case '\v':
  1072. case '\n':
  1073. /* go to first col if the mode is set */
  1074. tnewline(IS_SET(MODE_CRLF));
  1075. break;
  1076. case '\a':
  1077. if(!(xw.state & WIN_FOCUSED))
  1078. xseturgency(1);
  1079. break;
  1080. case '\033':
  1081. csireset();
  1082. term.esc = ESC_START;
  1083. break;
  1084. default:
  1085. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1086. tnewline(1); /* always go to first col */
  1087. tsetchar(c);
  1088. if(term.c.x+1 < term.col)
  1089. tmoveto(term.c.x+1, term.c.y);
  1090. else
  1091. term.c.state |= CURSOR_WRAPNEXT;
  1092. break;
  1093. }
  1094. }
  1095. }
  1096. void
  1097. tputs(char *s, int len) {
  1098. for(; len > 0; len--)
  1099. tputc(*s++);
  1100. }
  1101. void
  1102. tresize(int col, int row) {
  1103. int i, x;
  1104. int minrow = MIN(row, term.row);
  1105. int mincol = MIN(col, term.col);
  1106. int slide = term.c.y - row + 1;
  1107. if(col < 1 || row < 1)
  1108. return;
  1109. /* free unneeded rows */
  1110. i = 0;
  1111. if(slide > 0) {
  1112. /* slide screen to keep cursor where we expect it -
  1113. * tscrollup would work here, but we can optimize to
  1114. * memmove because we're freeing the earlier lines */
  1115. for(/* i = 0 */; i < slide; i++) {
  1116. free(term.line[i]);
  1117. free(term.alt[i]);
  1118. }
  1119. memmove(term.line, term.line + slide, row * sizeof(Line));
  1120. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1121. }
  1122. for(i += row; i < term.row; i++) {
  1123. free(term.line[i]);
  1124. free(term.alt[i]);
  1125. }
  1126. /* resize to new height */
  1127. term.line = realloc(term.line, row * sizeof(Line));
  1128. term.alt = realloc(term.alt, row * sizeof(Line));
  1129. /* resize each row to new width, zero-pad if needed */
  1130. for(i = 0; i < minrow; i++) {
  1131. term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
  1132. term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
  1133. for(x = mincol; x < col; x++) {
  1134. term.line[i][x].state = 0;
  1135. term.alt[i][x].state = 0;
  1136. }
  1137. }
  1138. /* allocate any new rows */
  1139. for(/* i == minrow */; i < row; i++) {
  1140. term.line[i] = calloc(col, sizeof(Glyph));
  1141. term.alt [i] = calloc(col, sizeof(Glyph));
  1142. }
  1143. /* update terminal size */
  1144. term.col = col, term.row = row;
  1145. /* make use of the LIMIT in tmoveto */
  1146. tmoveto(term.c.x, term.c.y);
  1147. /* reset scrolling region */
  1148. tsetscroll(0, row-1);
  1149. }
  1150. void
  1151. xloadcols(void) {
  1152. int i, r, g, b;
  1153. XColor color;
  1154. unsigned long white = WhitePixel(xw.dis, xw.scr);
  1155. for(i = 0; i < 16; i++) {
  1156. if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
  1157. dc.col[i] = white;
  1158. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1159. } else
  1160. dc.col[i] = color.pixel;
  1161. }
  1162. /* same colors as xterm */
  1163. for(r = 0; r < 6; r++)
  1164. for(g = 0; g < 6; g++)
  1165. for(b = 0; b < 6; b++) {
  1166. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1167. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1168. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1169. if (!XAllocColor(xw.dis, xw.cmap, &color)) {
  1170. dc.col[i] = white;
  1171. fprintf(stderr, "Could not allocate color %d\n", i);
  1172. } else
  1173. dc.col[i] = color.pixel;
  1174. i++;
  1175. }
  1176. for(r = 0; r < 24; r++, i++) {
  1177. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1178. if (!XAllocColor(xw.dis, xw.cmap, &color)) {
  1179. dc.col[i] = white;
  1180. fprintf(stderr, "Could not allocate color %d\n", i);
  1181. } else
  1182. dc.col[i] = color.pixel;
  1183. }
  1184. }
  1185. void
  1186. xclear(int x1, int y1, int x2, int y2) {
  1187. XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
  1188. XFillRectangle(xw.dis, xw.buf, dc.gc,
  1189. x1 * xw.cw, y1 * xw.ch,
  1190. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1191. }
  1192. void
  1193. xhints(void)
  1194. {
  1195. XClassHint class = {TNAME, TNAME};
  1196. XWMHints wm = {.flags = InputHint, .input = 1};
  1197. XSizeHints size = {
  1198. .flags = PSize | PResizeInc | PBaseSize,
  1199. .height = xw.h,
  1200. .width = xw.w,
  1201. .height_inc = xw.ch,
  1202. .width_inc = xw.cw,
  1203. .base_height = 2*BORDER,
  1204. .base_width = 2*BORDER,
  1205. };
  1206. XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
  1207. }
  1208. void
  1209. xinit(void) {
  1210. XSetWindowAttributes attrs;
  1211. if(!(xw.dis = XOpenDisplay(NULL)))
  1212. die("Can't open display\n");
  1213. xw.scr = XDefaultScreen(xw.dis);
  1214. /* font */
  1215. if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
  1216. die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
  1217. /* XXX: Assuming same size for bold font */
  1218. xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
  1219. xw.ch = dc.font->ascent + dc.font->descent;
  1220. /* colors */
  1221. xw.cmap = XDefaultColormap(xw.dis, xw.scr);
  1222. xloadcols();
  1223. /* window - default size */
  1224. xw.bufh = 24 * xw.ch;
  1225. xw.bufw = 80 * xw.cw;
  1226. xw.h = xw.bufh + 2*BORDER;
  1227. xw.w = xw.bufw + 2*BORDER;
  1228. attrs.background_pixel = dc.col[DefaultBG];
  1229. attrs.border_pixel = dc.col[DefaultBG];
  1230. attrs.bit_gravity = NorthWestGravity;
  1231. attrs.event_mask = FocusChangeMask | KeyPressMask
  1232. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1233. | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
  1234. attrs.colormap = xw.cmap;
  1235. xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
  1236. xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
  1237. XDefaultVisual(xw.dis, xw.scr),
  1238. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1239. | CWColormap,
  1240. &attrs);
  1241. xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
  1242. /* input methods */
  1243. xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
  1244. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1245. | XIMStatusNothing, XNClientWindow, xw.win,
  1246. XNFocusWindow, xw.win, NULL);
  1247. /* gc */
  1248. dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
  1249. XMapWindow(xw.dis, xw.win);
  1250. xhints();
  1251. XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
  1252. XSync(xw.dis, 0);
  1253. }
  1254. void
  1255. xdraws(char *s, Glyph base, int x, int y, int len) {
  1256. unsigned long xfg, xbg;
  1257. int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
  1258. int i;
  1259. if(base.mode & ATTR_REVERSE)
  1260. xfg = dc.col[base.bg], xbg = dc.col[base.fg];
  1261. else
  1262. xfg = dc.col[base.fg], xbg = dc.col[base.bg];
  1263. XSetBackground(xw.dis, dc.gc, xbg);
  1264. XSetForeground(xw.dis, dc.gc, xfg);
  1265. if(base.mode & ATTR_GFX)
  1266. for(i = 0; i < len; i++) {
  1267. char c = gfx[(unsigned int)s[i] % 256];
  1268. if(c)
  1269. s[i] = c;
  1270. else if(s[i] > 0x5f)
  1271. s[i] -= 0x5f;
  1272. }
  1273. XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
  1274. XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
  1275. if(base.mode & ATTR_UNDERLINE)
  1276. XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1277. }
  1278. void
  1279. xdrawcursor(void) {
  1280. static int oldx = 0;
  1281. static int oldy = 0;
  1282. Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
  1283. LIMIT(oldx, 0, term.col-1);
  1284. LIMIT(oldy, 0, term.row-1);
  1285. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1286. g.c = term.line[term.c.y][term.c.x].c;
  1287. /* remove the old cursor */
  1288. if(term.line[oldy][oldx].state & GLYPH_SET)
  1289. xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
  1290. else
  1291. xclear(oldx, oldy, oldx, oldy);
  1292. /* draw the new one */
  1293. if(!(term.c.state & CURSOR_HIDE) && (xw.state & WIN_FOCUSED)) {
  1294. xdraws(&g.c, g, term.c.x, term.c.y, 1);
  1295. oldx = term.c.x, oldy = term.c.y;
  1296. }
  1297. }
  1298. #ifdef DEBUG
  1299. /* basic drawing routines */
  1300. void
  1301. xdrawc(int x, int y, Glyph g) {
  1302. XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
  1303. XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
  1304. XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
  1305. XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
  1306. XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
  1307. }
  1308. void
  1309. draw(int dummy) {
  1310. int x, y;
  1311. xclear(0, 0, term.col-1, term.row-1);
  1312. for(y = 0; y < term.row; y++)
  1313. for(x = 0; x < term.col; x++)
  1314. if(term.line[y][x].state & GLYPH_SET)
  1315. xdrawc(x, y, term.line[y][x]);
  1316. xdrawcursor();
  1317. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1318. XFlush(xw.dis);
  1319. }
  1320. #else
  1321. /* optimized drawing routine */
  1322. void
  1323. draw(int redraw_all) {
  1324. int i, x, y, ox;
  1325. Glyph base, new;
  1326. char buf[DRAW_BUF_SIZ];
  1327. if(!(xw.state & WIN_VISIBLE))
  1328. return;
  1329. xclear(0, 0, term.col-1, term.row-1);
  1330. for(y = 0; y < term.row; y++) {
  1331. base = term.line[y][0];
  1332. i = ox = 0;
  1333. for(x = 0; x < term.col; x++) {
  1334. new = term.line[y][x];
  1335. if(sel.bx!=-1 && new.c && selected(x, y))
  1336. new.mode ^= ATTR_REVERSE;
  1337. if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1338. i >= DRAW_BUF_SIZ)) {
  1339. xdraws(buf, base, ox, y, i);
  1340. i = 0;
  1341. }
  1342. if(new.state & GLYPH_SET) {
  1343. if(i == 0) {
  1344. ox = x;
  1345. base = new;
  1346. }
  1347. buf[i++] = new.c;
  1348. }
  1349. }
  1350. if(i > 0)
  1351. xdraws(buf, base, ox, y, i);
  1352. }
  1353. xdrawcursor();
  1354. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1355. }
  1356. #endif
  1357. void
  1358. expose(XEvent *ev) {
  1359. XExposeEvent *e = &ev->xexpose;
  1360. if(xw.state & WIN_REDRAW) {
  1361. if(!e->count) {
  1362. xw.state &= ~WIN_REDRAW;
  1363. draw(SCREEN_REDRAW);
  1364. }
  1365. } else
  1366. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
  1367. e->width, e->height, e->x, e->y);
  1368. }
  1369. void
  1370. visibility(XEvent *ev) {
  1371. XVisibilityEvent *e = &ev->xvisibility;
  1372. if(e->state == VisibilityFullyObscured)
  1373. xw.state &= ~WIN_VISIBLE;
  1374. else if(!(xw.state & WIN_VISIBLE))
  1375. /* need a full redraw for next Expose, not just a buf copy */
  1376. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1377. }
  1378. void
  1379. unmap(XEvent *ev) {
  1380. xw.state &= ~WIN_VISIBLE;
  1381. }
  1382. void
  1383. xseturgency(int add) {
  1384. XWMHints *h = XGetWMHints(xw.dis, xw.win);
  1385. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1386. XSetWMHints(xw.dis, xw.win, h);
  1387. XFree(h);
  1388. }
  1389. void
  1390. focus(XEvent *ev) {
  1391. if(ev->type == FocusIn) {
  1392. xw.state |= WIN_FOCUSED;
  1393. xseturgency(0);
  1394. } else
  1395. xw.state &= ~WIN_FOCUSED;
  1396. draw(SCREEN_UPDATE);
  1397. }
  1398. char*
  1399. kmap(KeySym k) {
  1400. int i;
  1401. for(i = 0; i < LEN(key); i++)
  1402. if(key[i].k == k)
  1403. return (char*)key[i].s;
  1404. return NULL;
  1405. }
  1406. void
  1407. kpress(XEvent *ev) {
  1408. XKeyEvent *e = &ev->xkey;
  1409. KeySym ksym;
  1410. char buf[32];
  1411. char *customkey;
  1412. int len;
  1413. int meta;
  1414. int shift;
  1415. Status status;
  1416. meta = e->state & Mod1Mask;
  1417. shift = e->state & ShiftMask;
  1418. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1419. /* 1. custom keys from config.h */
  1420. if((customkey = kmap(ksym)))
  1421. ttywrite(customkey, strlen(customkey));
  1422. /* 2. hardcoded (overrides X lookup) */
  1423. else
  1424. switch(ksym) {
  1425. case XK_Up:
  1426. case XK_Down:
  1427. case XK_Left:
  1428. case XK_Right:
  1429. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
  1430. ttywrite(buf, 3);
  1431. break;
  1432. case XK_Insert:
  1433. if(shift)
  1434. selpaste();
  1435. break;
  1436. case XK_Return:
  1437. if(IS_SET(MODE_CRLF))
  1438. ttywrite("\r\n", 2);
  1439. else
  1440. ttywrite("\r", 1);
  1441. break;
  1442. /* 3. X lookup */
  1443. default:
  1444. if(len > 0) {
  1445. buf[sizeof(buf)-1] = '\0';
  1446. if(meta && len == 1)
  1447. ttywrite("\033", 1);
  1448. ttywrite(buf, len);
  1449. } else /* 4. nothing to send */
  1450. fprintf(stderr, "errkey: %d\n", (int)ksym);
  1451. break;
  1452. }
  1453. }
  1454. void
  1455. resize(XEvent *e) {
  1456. int col, row;
  1457. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  1458. return;
  1459. xw.w = e->xconfigure.width;
  1460. xw.h = e->xconfigure.height;
  1461. xw.bufw = xw.w - 2*BORDER;
  1462. xw.bufh = xw.h - 2*BORDER;
  1463. col = xw.bufw / xw.cw;
  1464. row = xw.bufh / xw.ch;
  1465. tresize(col, row);
  1466. ttyresize(col, row);
  1467. xw.bufh = MAX(1, xw.bufh);
  1468. xw.bufw = MAX(1, xw.bufw);
  1469. XFreePixmap(xw.dis, xw.buf);
  1470. xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
  1471. }
  1472. void
  1473. run(void) {
  1474. XEvent ev;
  1475. fd_set rfd;
  1476. int xfd = XConnectionNumber(xw.dis);
  1477. for(;;) {
  1478. FD_ZERO(&rfd);
  1479. FD_SET(cmdfd, &rfd);
  1480. FD_SET(xfd, &rfd);
  1481. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
  1482. if(errno == EINTR)
  1483. continue;
  1484. die("select failed: %s\n", SERRNO);
  1485. }
  1486. if(FD_ISSET(cmdfd, &rfd)) {
  1487. ttyread();
  1488. draw(SCREEN_UPDATE);
  1489. }
  1490. while(XPending(xw.dis)) {
  1491. XNextEvent(xw.dis, &ev);
  1492. if (XFilterEvent(&ev, xw.win))
  1493. continue;
  1494. if(handler[ev.type])
  1495. (handler[ev.type])(&ev);
  1496. }
  1497. }
  1498. }
  1499. int
  1500. main(int argc, char *argv[]) {
  1501. int i;
  1502. for(i = 1; i < argc; i++) {
  1503. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  1504. case 't':
  1505. if(++i < argc) opt_title = argv[i];
  1506. break;
  1507. case 'e':
  1508. if(++i < argc) opt_cmd = argv[i];
  1509. break;
  1510. case 'v':
  1511. default:
  1512. die(USAGE);
  1513. }
  1514. }
  1515. setlocale(LC_CTYPE, "");
  1516. tnew(80, 24);
  1517. ttynew();
  1518. xinit();
  1519. selinit();
  1520. run();
  1521. return 0;
  1522. }