Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1235 lines
26 KiB

  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/keysym.h>
  21. #include <X11/Xutil.h>
  22. #define TNAME "xterm"
  23. /* Arbitrary sizes */
  24. #define ESC_TITLE_SIZ 256
  25. #define ESC_BUF_SIZ 256
  26. #define ESC_ARG_SIZ 16
  27. #define DRAW_BUF_SIZ 1024
  28. #define SERRNO strerror(errno)
  29. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  30. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  31. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  32. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  33. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  34. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  35. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  36. /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
  37. enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
  38. enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT, CURSOR_HIDE, CURSOR_DRAW, CURSOR_SAVE, CURSOR_LOAD };
  39. enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
  40. enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4 };
  41. enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
  42. enum { SCREEN_UPDATE, SCREEN_REDRAW };
  43. typedef struct {
  44. char c; /* character code */
  45. char mode; /* attribute flags */
  46. int fg; /* foreground */
  47. int bg; /* background */
  48. char state; /* state flags */
  49. } Glyph;
  50. typedef Glyph* Line;
  51. typedef struct {
  52. Glyph attr; /* current char attributes */
  53. char hidden;
  54. int x;
  55. int y;
  56. } TCursor;
  57. /* CSI Escape sequence structs */
  58. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  59. typedef struct {
  60. char buf[ESC_BUF_SIZ]; /* raw string */
  61. int len; /* raw string length */
  62. char priv;
  63. int arg[ESC_ARG_SIZ];
  64. int narg; /* nb of args */
  65. char mode;
  66. } CSIEscape;
  67. /* Internal representation of the screen */
  68. typedef struct {
  69. int row; /* nb row */
  70. int col; /* nb col */
  71. Line* line; /* screen */
  72. TCursor c; /* cursor */
  73. int top; /* top scroll limit */
  74. int bot; /* bottom scroll limit */
  75. int mode; /* terminal mode flags */
  76. int esc; /* escape state flags */
  77. char title[ESC_TITLE_SIZ];
  78. int titlelen;
  79. } Term;
  80. /* Purely graphic info */
  81. typedef struct {
  82. Display* dis;
  83. Window win;
  84. int scr;
  85. int w; /* window width */
  86. int h; /* window height */
  87. int ch; /* char height */
  88. int cw; /* char width */
  89. } XWindow;
  90. typedef struct {
  91. KeySym k;
  92. char s[ESC_BUF_SIZ];
  93. } Key;
  94. #include "config.h"
  95. /* Drawing Context */
  96. typedef struct {
  97. unsigned long col[LEN(colorname)];
  98. XFontStruct* font;
  99. GC gc;
  100. } DC;
  101. static void die(const char *errstr, ...);
  102. static void draw(int);
  103. static void execsh(void);
  104. static void sigchld(int);
  105. static void run(void);
  106. static void csidump(void);
  107. static void csihandle(void);
  108. static void csiparse(void);
  109. static void csireset(void);
  110. static void tclearregion(int, int, int, int);
  111. static void tcursor(int);
  112. static void tmovecursor(int);
  113. static void tdeletechar(int);
  114. static void tdeleteline(int);
  115. static void tinsertblank(int);
  116. static void tinsertblankline(int);
  117. static void tmoveto(int, int);
  118. static void tnew(int, int);
  119. static void tnewline(void);
  120. static void tputc(char);
  121. static void tputs(char*, int);
  122. static void tresize(int, int);
  123. static void tscroll(void);
  124. static void tsetattr(int*, int);
  125. static void tsetchar(char);
  126. static void tsetscroll(int, int);
  127. static void ttynew(void);
  128. static void ttyread(void);
  129. static void ttyresize(int, int);
  130. static void ttywrite(const char *, size_t);
  131. static unsigned long xgetcol(const char *);
  132. static void xclear(int, int, int, int);
  133. static void xcursor(int);
  134. static void xdrawc(int, int, Glyph);
  135. static void xinit(void);
  136. static void xscroll(void);
  137. static void expose(XEvent *);
  138. static char * kmap(KeySym);
  139. static void kpress(XEvent *);
  140. static void resize(XEvent *);
  141. static void (*handler[LASTEvent])(XEvent *) = {
  142. [KeyPress] = kpress,
  143. [Expose] = expose,
  144. [ConfigureNotify] = resize
  145. };
  146. /* Globals */
  147. static DC dc;
  148. static XWindow xw;
  149. static Term term;
  150. static CSIEscape escseq;
  151. static int cmdfd;
  152. static pid_t pid;
  153. static int running;
  154. #ifdef DEBUG
  155. void
  156. tdump(void) {
  157. int row, col;
  158. Glyph c;
  159. for(row = 0; row < term.row; row++) {
  160. for(col = 0; col < term.col; col++) {
  161. if(col == term.c.x && row == term.c.y)
  162. putchar('#');
  163. else {
  164. c = term.line[row][col];
  165. putchar(c.state & GLYPH_SET ? c.c : '.');
  166. }
  167. }
  168. putchar('\n');
  169. }
  170. }
  171. #endif
  172. void
  173. die(const char *errstr, ...) {
  174. va_list ap;
  175. va_start(ap, errstr);
  176. vfprintf(stderr, errstr, ap);
  177. va_end(ap);
  178. exit(EXIT_FAILURE);
  179. }
  180. void
  181. execsh(void) {
  182. char *args[3] = {SHELL, "-i", NULL};
  183. putenv("TERM=" TNAME);
  184. execvp(SHELL, args);
  185. }
  186. void
  187. xbell(void) { /* visual bell */
  188. XRectangle r = { 0, 0, xw.w, xw.h };
  189. XSetForeground(xw.dis, dc.gc, dc.col[BellCol]);
  190. XFillRectangles(xw.dis, xw.win, dc.gc, &r, 1);
  191. /* usleep(30000); */
  192. draw(SCREEN_REDRAW);
  193. }
  194. void
  195. sigchld(int a) {
  196. int stat = 0;
  197. if(waitpid(pid, &stat, 0) < 0)
  198. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  199. if(WIFEXITED(stat))
  200. exit(WEXITSTATUS(stat));
  201. else
  202. exit(EXIT_FAILURE);
  203. }
  204. void
  205. ttynew(void) {
  206. int m, s;
  207. char *pts;
  208. if((m = posix_openpt(O_RDWR | O_NOCTTY)) < 0)
  209. die("openpt failed: %s\n", SERRNO);
  210. if(grantpt(m) < 0)
  211. die("grandpt failed: %s\n", SERRNO);
  212. if(unlockpt(m) < 0)
  213. die("unlockpt failed: %s\n", SERRNO);
  214. if(!(pts = ptsname(m)))
  215. die("ptsname failed: %s\n", SERRNO);
  216. if((s = open(pts, O_RDWR | O_NOCTTY)) < 0)
  217. die("Couldn't open slave: %s\n", SERRNO);
  218. fcntl(s, F_SETFL, O_NDELAY);
  219. switch(pid = fork()) {
  220. case -1:
  221. die("fork failed\n");
  222. break;
  223. case 0:
  224. setsid(); /* create a new process group */
  225. dup2(s, STDIN_FILENO);
  226. dup2(s, STDOUT_FILENO);
  227. dup2(s, STDERR_FILENO);
  228. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  229. die("ioctl TTIOCSTTY failed: %s\n", SERRNO);
  230. execsh();
  231. break;
  232. default:
  233. close(s);
  234. cmdfd = m;
  235. signal(SIGCHLD, sigchld);
  236. }
  237. }
  238. void
  239. dump(char c) {
  240. static int col;
  241. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  242. if(++col % 10 == 0)
  243. fprintf(stderr, "\n");
  244. }
  245. void
  246. ttyread(void) {
  247. char buf[BUFSIZ] = {0};
  248. int ret;
  249. if((ret = read(cmdfd, buf, BUFSIZ)) < 0)
  250. die("Couldn't read from shell: %s\n", SERRNO);
  251. else
  252. tputs(buf, ret);
  253. }
  254. void
  255. ttywrite(const char *s, size_t n) {
  256. if(write(cmdfd, s, n) == -1)
  257. die("write error on tty: %s\n", SERRNO);
  258. }
  259. void
  260. ttyresize(int x, int y) {
  261. struct winsize w;
  262. w.ws_row = term.row;
  263. w.ws_col = term.col;
  264. w.ws_xpixel = w.ws_ypixel = 0;
  265. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  266. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  267. }
  268. void
  269. tcursor(int mode) {
  270. static TCursor c;
  271. if(mode == CURSOR_SAVE)
  272. c = term.c;
  273. else if(mode == CURSOR_LOAD)
  274. term.c = c, tmoveto(c.x, c.y);
  275. }
  276. void
  277. tnew(int col, int row) { /* screen size */
  278. term.row = row, term.col = col;
  279. term.top = 0, term.bot = term.row - 1;
  280. /* mode */
  281. term.mode = MODE_WRAP;
  282. /* cursor */
  283. term.c.attr.mode = ATTR_NULL;
  284. term.c.attr.fg = DefaultFG;
  285. term.c.attr.bg = DefaultBG;
  286. term.c.x = term.c.y = 0;
  287. term.c.hidden = 0;
  288. /* allocate screen */
  289. term.line = calloc(term.row, sizeof(Line));
  290. for(row = 0 ; row < term.row; row++)
  291. term.line[row] = calloc(term.col, sizeof(Glyph));
  292. }
  293. void
  294. tscroll(void) {
  295. Line temp = term.line[term.top];
  296. int i;
  297. /* X stuff _before_ the line swapping (results in wrong line index) */
  298. xscroll();
  299. for(i = term.top; i < term.bot; i++)
  300. term.line[i] = term.line[i+1];
  301. memset(temp, 0, sizeof(Glyph) * term.col);
  302. term.line[term.bot] = temp;
  303. }
  304. void
  305. tnewline(void) {
  306. int y = term.c.y + 1;
  307. if(y > term.bot)
  308. tscroll(), y = term.bot;
  309. tmoveto(0, y);
  310. }
  311. void
  312. csiparse(void) {
  313. /* int noarg = 1; */
  314. char *p = escseq.buf;
  315. escseq.narg = 0;
  316. if(*p == '?')
  317. escseq.priv = 1, p++;
  318. while(p < escseq.buf+escseq.len) {
  319. while(isdigit(*p)) {
  320. escseq.arg[escseq.narg] *= 10;
  321. escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
  322. }
  323. if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
  324. escseq.narg++, p++;
  325. else {
  326. escseq.mode = *p;
  327. escseq.narg++;
  328. return;
  329. }
  330. }
  331. }
  332. void
  333. tmoveto(int x, int y) {
  334. term.c.x = x < 0 ? 0 : x >= term.col ? term.col-1 : x;
  335. term.c.y = y < 0 ? 0 : y >= term.row ? term.row-1 : y;
  336. }
  337. void
  338. tmovecursor(int dir) {
  339. int xf = term.c.x, yf = term.c.y;
  340. switch(dir) {
  341. case CURSOR_UP:
  342. yf--;
  343. break;
  344. case CURSOR_DOWN:
  345. yf++;
  346. break;
  347. case CURSOR_LEFT:
  348. xf--;
  349. if(term.mode & MODE_WRAP && xf < 0) {
  350. xf = term.col-1, yf--;
  351. if(yf < term.top)
  352. yf = term.top, xf = 0;
  353. }
  354. break;
  355. case CURSOR_RIGHT:
  356. xf++;
  357. if(term.mode & MODE_WRAP && xf >= term.col) {
  358. xf = 0, yf++;
  359. if(yf > term.bot)
  360. yf = term.bot, tscroll();
  361. }
  362. break;
  363. }
  364. tmoveto(xf, yf);
  365. }
  366. void
  367. tsetchar(char c) {
  368. term.line[term.c.y][term.c.x] = term.c.attr;
  369. term.line[term.c.y][term.c.x].c = c;
  370. term.line[term.c.y][term.c.x].state |= GLYPH_SET | GLYPH_DIRTY;
  371. }
  372. void
  373. tclearregion(int x1, int y1, int x2, int y2) {
  374. int x, y;
  375. LIMIT(x1, 0, term.col-1);
  376. LIMIT(x2, 0, term.col-1);
  377. LIMIT(y1, 0, term.row-1);
  378. LIMIT(y2, 0, term.row-1);
  379. /* XXX: could be optimized */
  380. for(x = x1; x <= x2; x++)
  381. for(y = y1; y <= y2; y++)
  382. memset(&term.line[y][x], 0, sizeof(Glyph));
  383. xclear(x1, y1, x2, y2);
  384. }
  385. void
  386. tdeletechar(int n) {
  387. int src = term.c.x + n;
  388. int dst = term.c.x;
  389. int size = term.col - src;
  390. if(src >= term.col) {
  391. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  392. return;
  393. }
  394. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  395. tclearregion(term.col-size, term.c.y, term.col-1, term.c.y);
  396. }
  397. void
  398. tinsertblank(int n) {
  399. int src = term.c.x;
  400. int dst = src + n;
  401. int size = term.col - n - src;
  402. if(dst >= term.col) {
  403. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  404. return;
  405. }
  406. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  407. tclearregion(src, term.c.y, dst, term.c.y);
  408. }
  409. void
  410. tsetlinestate(int n, int state) {
  411. int i;
  412. for(i = 0; i < term.col; i++)
  413. term.line[n][i].state |= state;
  414. }
  415. void
  416. tinsertblankline(int n) {
  417. int i;
  418. Line blank;
  419. int bot = term.bot;
  420. if(term.c.y > term.bot)
  421. bot = term.row - 1;
  422. else if(term.c.y < term.top)
  423. bot = term.top - 1;
  424. if(term.c.y + n >= bot) {
  425. tclearregion(0, term.c.y, term.col-1, bot);
  426. return;
  427. }
  428. for(i = bot; i >= term.c.y+n; i--) {
  429. /* swap deleted line <-> blanked line */
  430. blank = term.line[i];
  431. term.line[i] = term.line[i-n];
  432. term.line[i-n] = blank;
  433. /* blank it */
  434. memset(blank, 0, term.col * sizeof(Glyph));
  435. tsetlinestate(i, GLYPH_DIRTY);
  436. tsetlinestate(i-n, GLYPH_DIRTY);
  437. }
  438. }
  439. void
  440. tdeleteline(int n) {
  441. int i;
  442. Line blank;
  443. int bot = term.bot;
  444. if(term.c.y > term.bot)
  445. bot = term.row - 1;
  446. else if(term.c.y < term.top)
  447. bot = term.top - 1;
  448. if(term.c.y + n >= bot) {
  449. tclearregion(0, term.c.y, term.col-1, bot);
  450. return;
  451. }
  452. for(i = term.c.y; i <= bot-n; i++) {
  453. /* swap deleted line <-> blanked line */
  454. blank = term.line[i];
  455. term.line[i] = term.line[i+n];
  456. term.line[i+n] = blank;
  457. /* blank it */
  458. memset(blank, 0, term.col * sizeof(Glyph));
  459. tsetlinestate(i, GLYPH_DIRTY);
  460. tsetlinestate(i-n, GLYPH_DIRTY);
  461. }
  462. }
  463. void
  464. tsetattr(int *attr, int l) {
  465. int i;
  466. for(i = 0; i < l; i++) {
  467. switch(attr[i]) {
  468. case 0:
  469. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
  470. term.c.attr.fg = DefaultFG;
  471. term.c.attr.bg = DefaultBG;
  472. break;
  473. case 1:
  474. term.c.attr.mode |= ATTR_BOLD;
  475. break;
  476. case 4:
  477. term.c.attr.mode |= ATTR_UNDERLINE;
  478. break;
  479. case 7:
  480. term.c.attr.mode |= ATTR_REVERSE;
  481. break;
  482. case 8:
  483. term.c.hidden = CURSOR_HIDE;
  484. break;
  485. case 22:
  486. term.c.attr.mode &= ~ATTR_BOLD;
  487. break;
  488. case 24:
  489. term.c.attr.mode &= ~ATTR_UNDERLINE;
  490. break;
  491. case 27:
  492. term.c.attr.mode &= ~ATTR_REVERSE;
  493. break;
  494. case 39:
  495. term.c.attr.fg = DefaultFG;
  496. break;
  497. case 49:
  498. term.c.attr.fg = DefaultBG;
  499. break;
  500. default:
  501. if(BETWEEN(attr[i], 30, 37))
  502. term.c.attr.fg = attr[i] - 30;
  503. else if(BETWEEN(attr[i], 40, 47))
  504. term.c.attr.bg = attr[i] - 40;
  505. break;
  506. }
  507. }
  508. }
  509. void
  510. tsetscroll(int t, int b) {
  511. int temp;
  512. LIMIT(t, 0, term.row-1);
  513. LIMIT(b, 0, term.row-1);
  514. if(t > b) {
  515. temp = t;
  516. t = b;
  517. b = temp;
  518. }
  519. term.top = t;
  520. term.bot = b;
  521. }
  522. void
  523. csihandle(void) {
  524. switch(escseq.mode) {
  525. default:
  526. unknown:
  527. printf("erresc: unknown sequence -- ");
  528. csidump();
  529. /* die(""); */
  530. break;
  531. case '@': /* ICH -- Insert <n> blank char */
  532. DEFAULT(escseq.arg[0], 1);
  533. tinsertblank(escseq.arg[0]);
  534. break;
  535. case 'A': /* CUU -- Cursor <n> Up */
  536. case 'e':
  537. DEFAULT(escseq.arg[0], 1);
  538. tmoveto(term.c.x, term.c.y-escseq.arg[0]);
  539. break;
  540. case 'B': /* CUD -- Cursor <n> Down */
  541. DEFAULT(escseq.arg[0], 1);
  542. tmoveto(term.c.x, term.c.y+escseq.arg[0]);
  543. break;
  544. case 'C': /* CUF -- Cursor <n> Forward */
  545. case 'a':
  546. DEFAULT(escseq.arg[0], 1);
  547. tmoveto(term.c.x+escseq.arg[0], term.c.y);
  548. break;
  549. case 'D': /* CUB -- Cursor <n> Backward */
  550. DEFAULT(escseq.arg[0], 1);
  551. tmoveto(term.c.x-escseq.arg[0], term.c.y);
  552. break;
  553. case 'E': /* CNL -- Cursor <n> Down and first col */
  554. DEFAULT(escseq.arg[0], 1);
  555. tmoveto(0, term.c.y+escseq.arg[0]);
  556. break;
  557. case 'F': /* CPL -- Cursor <n> Up and first col */
  558. DEFAULT(escseq.arg[0], 1);
  559. tmoveto(0, term.c.y-escseq.arg[0]);
  560. break;
  561. case 'G': /* CHA -- Move to <col> */
  562. case '`': /* XXX: HPA -- same? */
  563. DEFAULT(escseq.arg[0], 1);
  564. tmoveto(escseq.arg[0]-1, term.c.y);
  565. break;
  566. case 'H': /* CUP -- Move to <row> <col> */
  567. case 'f': /* XXX: HVP -- same? */
  568. DEFAULT(escseq.arg[0], 1);
  569. DEFAULT(escseq.arg[1], 1);
  570. tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
  571. break;
  572. /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
  573. case 'J': /* ED -- Clear screen */
  574. switch(escseq.arg[0]) {
  575. case 0: /* below */
  576. tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
  577. break;
  578. case 1: /* above */
  579. tclearregion(0, 0, term.c.x, term.c.y);
  580. break;
  581. case 2: /* all */
  582. tclearregion(0, 0, term.col-1, term.row-1);
  583. break;
  584. case 3: /* XXX: erase saved lines (xterm) */
  585. default:
  586. goto unknown;
  587. }
  588. break;
  589. case 'K': /* EL -- Clear line */
  590. switch(escseq.arg[0]) {
  591. case 0: /* right */
  592. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  593. break;
  594. case 1: /* left */
  595. tclearregion(0, term.c.y, term.c.x, term.c.y);
  596. break;
  597. case 2: /* all */
  598. tclearregion(0, term.c.y, term.col-1, term.c.y);
  599. break;
  600. }
  601. break;
  602. case 'S': /* XXX: SU -- Scroll <n> line up (faked) */
  603. case 'L': /* IL -- Insert <n> blank lines */
  604. DEFAULT(escseq.arg[0], 1);
  605. tinsertblankline(escseq.arg[0]);
  606. break;
  607. case 'l': /* RM -- Reset Mode */
  608. if(escseq.priv) {
  609. switch(escseq.arg[0]) {
  610. case 1:
  611. term.mode &= ~MODE_APPKEYPAD;
  612. break;
  613. case 7:
  614. term.mode &= ~MODE_WRAP;
  615. break;
  616. case 12: /* att610 -- Stop blinking cursor (IGNORED) */
  617. break;
  618. case 25:
  619. term.c.hidden = 1;
  620. break;
  621. case 1048: /* XXX: no alt. screen to erase/save */
  622. case 1049:
  623. tcursor(CURSOR_LOAD);
  624. tclearregion(0, 0, term.col-1, term.row-1);
  625. break;
  626. default:
  627. goto unknown;
  628. }
  629. } else {
  630. switch(escseq.arg[0]) {
  631. case 4:
  632. term.mode &= ~MODE_INSERT;
  633. break;
  634. default:
  635. goto unknown;
  636. }
  637. }
  638. break;
  639. case 'M': /* DL -- Delete <n> lines */
  640. DEFAULT(escseq.arg[0], 1);
  641. tdeleteline(escseq.arg[0]);
  642. break;
  643. case 'X': /* ECH -- Erase <n> char */
  644. DEFAULT(escseq.arg[0], 1);
  645. tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
  646. break;
  647. case 'P': /* DCH -- Delete <n> char */
  648. DEFAULT(escseq.arg[0], 1);
  649. tdeletechar(escseq.arg[0]);
  650. break;
  651. /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
  652. case 'd': /* VPA -- Move to <row> */
  653. DEFAULT(escseq.arg[0], 1);
  654. tmoveto(term.c.x, escseq.arg[0]-1);
  655. break;
  656. case 'h': /* SM -- Set terminal mode */
  657. if(escseq.priv) {
  658. switch(escseq.arg[0]) {
  659. case 1:
  660. term.mode |= MODE_APPKEYPAD;
  661. break;
  662. case 7:
  663. term.mode |= MODE_WRAP;
  664. break;
  665. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  666. break;
  667. case 25:
  668. term.c.hidden = 0;
  669. break;
  670. case 1048:
  671. case 1049: /* XXX: no alt. screen to erase/save */
  672. tcursor(CURSOR_SAVE);
  673. tclearregion(0, 0, term.col-1, term.row-1);
  674. break;
  675. default: goto unknown;
  676. }
  677. } else {
  678. switch(escseq.arg[0]) {
  679. case 4:
  680. term.mode |= MODE_INSERT;
  681. break;
  682. default: goto unknown;
  683. }
  684. };
  685. break;
  686. case 'm': /* SGR -- Terminal attribute (color) */
  687. tsetattr(escseq.arg, escseq.narg);
  688. break;
  689. case 'r': /* DECSTBM -- Set Scrolling Region */
  690. if(escseq.priv)
  691. goto unknown;
  692. else {
  693. DEFAULT(escseq.arg[0], 1);
  694. DEFAULT(escseq.arg[1], term.row);
  695. tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
  696. }
  697. break;
  698. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  699. tcursor(CURSOR_SAVE);
  700. break;
  701. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  702. tcursor(CURSOR_LOAD);
  703. break;
  704. }
  705. }
  706. void
  707. csidump(void) {
  708. int i;
  709. printf("ESC [ %s", escseq.priv ? "? " : "");
  710. if(escseq.narg)
  711. for(i = 0; i < escseq.narg; i++)
  712. printf("%d ", escseq.arg[i]);
  713. if(escseq.mode)
  714. putchar(escseq.mode);
  715. putchar('\n');
  716. }
  717. void
  718. csireset(void) {
  719. memset(&escseq, 0, sizeof(escseq));
  720. }
  721. void
  722. tputtab(void) {
  723. int space = TAB - term.c.x % TAB;
  724. if(term.c.x + space >= term.col)
  725. space--;
  726. for(; space > 0; space--)
  727. tmovecursor(CURSOR_RIGHT);
  728. }
  729. void
  730. tputc(char c) {
  731. /* dump(c); */
  732. if(term.esc & ESC_START) {
  733. if(term.esc & ESC_CSI) {
  734. escseq.buf[escseq.len++] = c;
  735. if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
  736. term.esc = 0;
  737. csiparse(), csihandle();
  738. }
  739. } else if(term.esc & ESC_OSC) {
  740. if(c == ';') {
  741. term.titlelen = 0;
  742. term.esc = ESC_START | ESC_TITLE;
  743. }
  744. } else if(term.esc & ESC_TITLE) {
  745. if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
  746. term.esc = 0;
  747. term.title[term.titlelen] = '\0';
  748. XStoreName(xw.dis, xw.win, term.title);
  749. } else {
  750. term.title[term.titlelen++] = c;
  751. }
  752. } else if(term.esc & ESC_ALTCHARSET) {
  753. switch(c) {
  754. case '0': /* Line drawing crap */
  755. term.c.attr.mode |= ATTR_GFX;
  756. break;
  757. case 'B': /* Back to regular text */
  758. term.c.attr.mode &= ~ATTR_GFX;
  759. break;
  760. default:
  761. printf("esc unhandled charset: ESC ( %c\n", c);
  762. }
  763. term.esc = 0;
  764. } else {
  765. switch(c) {
  766. case '[':
  767. term.esc |= ESC_CSI;
  768. break;
  769. case ']':
  770. term.esc |= ESC_OSC;
  771. break;
  772. case '(':
  773. term.esc |= ESC_ALTCHARSET;
  774. break;
  775. case 'A':
  776. tmoveto(term.c.x, term.c.y-1);
  777. term.esc = 0;
  778. break;
  779. case 'B':
  780. tmoveto(term.c.x, term.c.y+1);
  781. term.esc = 0;
  782. break;
  783. case 'C':
  784. tmoveto(term.c.x+1, term.c.y);
  785. term.esc = 0;
  786. break;
  787. case 'D':
  788. tmoveto(term.c.x-1, term.c.y);
  789. term.esc = 0;
  790. break;
  791. case '=': /* DECPAM */
  792. term.mode |= MODE_APPKEYPAD;
  793. term.esc = 0;
  794. break;
  795. case '>': /* DECPNM */
  796. term.mode &= ~MODE_APPKEYPAD;
  797. term.esc = 0;
  798. break;
  799. case '7':
  800. tcursor(CURSOR_SAVE);
  801. break;
  802. case '8':
  803. tcursor(CURSOR_LOAD);
  804. break;
  805. default:
  806. fprintf(stderr, "erresc: unknown sequence ESC %02X '%c'\n", c, isprint(c)?c:'.');
  807. term.esc = 0;
  808. }
  809. }
  810. } else {
  811. switch(c) {
  812. case '\t':
  813. tputtab();
  814. break;
  815. case '\b':
  816. tmovecursor(CURSOR_LEFT);
  817. break;
  818. case '\r':
  819. tmoveto(0, term.c.y);
  820. break;
  821. case '\n':
  822. tnewline();
  823. break;
  824. case '\a':
  825. xbell();
  826. break;
  827. case '\033':
  828. csireset();
  829. term.esc = ESC_START;
  830. break;
  831. default:
  832. tsetchar(c);
  833. tmovecursor(CURSOR_RIGHT);
  834. break;
  835. }
  836. }
  837. }
  838. void
  839. tputs(char *s, int len) {
  840. for(; len > 0; len--)
  841. tputc(*s++);
  842. }
  843. void
  844. tresize(int col, int row) {
  845. int i;
  846. Line *line;
  847. int minrow = MIN(row, term.row);
  848. int mincol = MIN(col, term.col);
  849. if(col < 1 || row < 1)
  850. return;
  851. /* alloc */
  852. line = calloc(row, sizeof(Line));
  853. for(i = 0 ; i < row; i++)
  854. line[i] = calloc(col, sizeof(Glyph));
  855. /* copy */
  856. for(i = 0 ; i < minrow; i++)
  857. memcpy(line[i], term.line[i], mincol * sizeof(Glyph));
  858. /* free */
  859. for(i = 0; i < term.row; i++)
  860. free(term.line[i]);
  861. free(term.line);
  862. LIMIT(term.c.x, 0, col-1);
  863. LIMIT(term.c.y, 0, row-1);
  864. LIMIT(term.top, 0, row-1);
  865. LIMIT(term.bot, 0, row-1);
  866. term.bot = row-1;
  867. term.line = line;
  868. term.col = col, term.row = row;
  869. }
  870. unsigned long
  871. xgetcol(const char *s) {
  872. XColor color;
  873. Colormap cmap = DefaultColormap(xw.dis, xw.scr);
  874. if(!XAllocNamedColor(xw.dis, cmap, s, &color, &color)) {
  875. color.pixel = WhitePixel(xw.dis, xw.scr);
  876. fprintf(stderr, "Could not allocate color '%s'\n", s);
  877. }
  878. return color.pixel;
  879. }
  880. void
  881. xclear(int x1, int y1, int x2, int y2) {
  882. XClearArea(xw.dis, xw.win,
  883. x1 * xw.cw, y1 * xw.ch,
  884. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch,
  885. False);
  886. }
  887. void
  888. xscroll(void) {
  889. int srcy = (term.top+1) * xw.ch;
  890. int dsty = term.top * xw.ch;
  891. int height = (term.bot-term.top) * xw.ch;
  892. xcursor(CURSOR_HIDE);
  893. XCopyArea(xw.dis, xw.win, xw.win, dc.gc, 0, srcy, xw.w, height, 0, dsty);
  894. xclear(0, term.bot, term.col-1, term.bot);
  895. }
  896. void
  897. xinit(void) {
  898. XGCValues values;
  899. unsigned long valuemask;
  900. XClassHint chint;
  901. XWMHints wmhint;
  902. XSizeHints shint;
  903. char *args[] = {NULL};
  904. int i;
  905. xw.dis = XOpenDisplay(NULL);
  906. xw.scr = XDefaultScreen(xw.dis);
  907. if(!xw.dis)
  908. die("Can't open display\n");
  909. /* font */
  910. if(!(dc.font = XLoadQueryFont(xw.dis, FONT)))
  911. die("Can't load font %s\n", FONT);
  912. xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
  913. xw.ch = dc.font->ascent + dc.font->descent + LINESPACE;
  914. /* colors */
  915. for(i = 0; i < LEN(colorname); i++)
  916. dc.col[i] = xgetcol(colorname[i]);
  917. term.c.attr.fg = DefaultFG;
  918. term.c.attr.bg = DefaultBG;
  919. term.c.attr.mode = ATTR_NULL;
  920. /* windows */
  921. xw.h = term.row * xw.ch;
  922. xw.w = term.col * xw.cw;
  923. /* XXX: this BORDER is useless after the first resize, handle it in xdraws() */
  924. xw.win = XCreateSimpleWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
  925. xw.w, xw.h, BORDER,
  926. dc.col[DefaultBG],
  927. dc.col[DefaultBG]);
  928. /* gc */
  929. values.foreground = XWhitePixel(xw.dis, xw.scr);
  930. values.font = dc.font->fid;
  931. valuemask = GCForeground | GCFont;
  932. dc.gc = XCreateGC(xw.dis, xw.win, valuemask, &values);
  933. XMapWindow(xw.dis, xw.win);
  934. /* wm stuff */
  935. chint.res_name = TNAME, chint.res_class = TNAME;
  936. wmhint.input = 1, wmhint.flags = InputHint;
  937. shint.height_inc = xw.ch, shint.width_inc = xw.cw;
  938. shint.height = xw.h, shint.width = xw.w;
  939. shint.flags = PSize | PResizeInc;
  940. XSetWMProperties(xw.dis, xw.win, NULL, NULL, &args[0], 0, &shint, &wmhint, &chint);
  941. XStoreName(xw.dis, xw.win, TNAME);
  942. XSync(xw.dis, 0);
  943. }
  944. void
  945. xdraws(char *s, Glyph base, int x, int y, int len) {
  946. unsigned long xfg, xbg;
  947. int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
  948. int i;
  949. if(base.mode & ATTR_REVERSE)
  950. xfg = dc.col[base.bg], xbg = dc.col[base.fg];
  951. else
  952. xfg = dc.col[base.fg], xbg = dc.col[base.bg];
  953. XSetBackground(xw.dis, dc.gc, xbg);
  954. XSetForeground(xw.dis, dc.gc, xfg);
  955. if(base.mode & ATTR_GFX)
  956. for(i = 0; i < len; i++)
  957. s[i] = gfx[s[i]];
  958. XDrawImageString(xw.dis, xw.win, dc.gc, winx, winy, s, len);
  959. if(base.mode & ATTR_UNDERLINE)
  960. XDrawLine(xw.dis, xw.win, dc.gc, winx, winy+1, winx+width-1, winy+1);
  961. }
  962. void
  963. xdrawc(int x, int y, Glyph g) {
  964. XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
  965. unsigned long xfg, xbg;
  966. /* reverse video */
  967. if(g.mode & ATTR_REVERSE)
  968. xfg = dc.col[g.bg], xbg = dc.col[g.fg];
  969. else
  970. xfg = dc.col[g.fg], xbg = dc.col[g.bg];
  971. /* background */
  972. XSetBackground(xw.dis, dc.gc, xbg);
  973. XSetForeground(xw.dis, dc.gc, xfg);
  974. XDrawImageString(xw.dis, xw.win, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
  975. }
  976. void
  977. xcursor(int mode) {
  978. static int oldx = 0;
  979. static int oldy = 0;
  980. Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
  981. LIMIT(oldx, 0, term.col-1);
  982. LIMIT(oldy, 0, term.row-1);
  983. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  984. g.c = term.line[term.c.y][term.c.x].c;
  985. /* remove the old cursor */
  986. if(term.line[oldy][oldx].state & GLYPH_SET)
  987. xdrawc(oldx, oldy, term.line[oldy][oldx]);
  988. else
  989. xclear(oldx, oldy, oldx, oldy);
  990. /* draw the new one */
  991. if(mode == CURSOR_DRAW) {
  992. xdrawc(term.c.x, term.c.y, g);
  993. oldx = term.c.x, oldy = term.c.y;
  994. }
  995. }
  996. void
  997. draw(int redraw_all) {
  998. int i, x, y, ox;
  999. Glyph base, new;
  1000. char buf[DRAW_BUF_SIZ];
  1001. for(y = 0; y < term.row; y++) {
  1002. base = term.line[y][0];
  1003. i = ox = 0;
  1004. for(x = 0; x < term.col; x++) {
  1005. new = term.line[y][x];
  1006. if(!ATTRCMP(base, new) && i < DRAW_BUF_SIZ)
  1007. buf[i++] = new.c;
  1008. else {
  1009. xdraws(buf, base, ox, y, i);
  1010. buf[0] = new.c;
  1011. i = 1;
  1012. ox = x;
  1013. base = new;
  1014. }
  1015. }
  1016. xdraws(buf, base, ox, y, i);
  1017. }
  1018. if(!term.c.hidden)
  1019. xcursor(CURSOR_DRAW);
  1020. }
  1021. void
  1022. expose(XEvent *ev) {
  1023. draw(SCREEN_REDRAW);
  1024. }
  1025. char*
  1026. kmap(KeySym k) {
  1027. int i;
  1028. for(i = 0; i < LEN(key); i++)
  1029. if(key[i].k == k)
  1030. return (char*)key[i].s;
  1031. return NULL;
  1032. }
  1033. void
  1034. kpress(XEvent *ev) {
  1035. XKeyEvent *e = &ev->xkey;
  1036. KeySym ksym;
  1037. char buf[32];
  1038. char *customkey;
  1039. int len;
  1040. int meta;
  1041. int shift;
  1042. meta = e->state & Mod1Mask;
  1043. shift = e->state & ShiftMask;
  1044. len = XLookupString(e, buf, sizeof(buf), &ksym, NULL);
  1045. if(customkey = kmap(ksym))
  1046. ttywrite(customkey, strlen(customkey));
  1047. else if(len > 0) {
  1048. buf[sizeof(buf)-1] = '\0';
  1049. if(meta && len == 1)
  1050. ttywrite("\033", 1);
  1051. ttywrite(buf, len);
  1052. } else
  1053. switch(ksym) {
  1054. case XK_Up:
  1055. case XK_Down:
  1056. case XK_Left:
  1057. case XK_Right:
  1058. sprintf(buf, "\033%c%c", term.mode & MODE_APPKEYPAD ? 'O' : '[', "DACB"[ksym - XK_Left]);
  1059. ttywrite(buf, 3);
  1060. break;
  1061. case XK_Insert:
  1062. if(shift)
  1063. /* XXX: paste X clipboard */;
  1064. break;
  1065. default:
  1066. fprintf(stderr, "errkey: %d\n", (int)ksym);
  1067. break;
  1068. }
  1069. }
  1070. void
  1071. resize(XEvent *e) {
  1072. int col, row;
  1073. col = e->xconfigure.width / xw.cw;
  1074. row = e->xconfigure.height / xw.ch;
  1075. if(term.col != col || term.row != row) {
  1076. tresize(col, row);
  1077. ttyresize(col, row);
  1078. xw.w = e->xconfigure.width;
  1079. xw.h = e->xconfigure.height;
  1080. draw(SCREEN_REDRAW);
  1081. }
  1082. }
  1083. void
  1084. run(void) {
  1085. XEvent ev;
  1086. fd_set rfd;
  1087. int xfd = XConnectionNumber(xw.dis);
  1088. running = 1;
  1089. XSelectInput(xw.dis, xw.win, ExposureMask | KeyPressMask | StructureNotifyMask);
  1090. XResizeWindow(xw.dis, xw.win, xw.w , xw.h); /* fix resize bug in wmii (?) */
  1091. while(running) {
  1092. FD_ZERO(&rfd);
  1093. FD_SET(cmdfd, &rfd);
  1094. FD_SET(xfd, &rfd);
  1095. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) == -1) {
  1096. if(errno == EINTR)
  1097. continue;
  1098. die("select failed: %s\n", SERRNO);
  1099. }
  1100. if(FD_ISSET(cmdfd, &rfd)) {
  1101. ttyread();
  1102. draw(SCREEN_UPDATE);
  1103. }
  1104. while(XPending(xw.dis)) {
  1105. XNextEvent(xw.dis, &ev);
  1106. if(handler[ev.type])
  1107. (handler[ev.type])(&ev);
  1108. }
  1109. }
  1110. }
  1111. int
  1112. main(int argc, char *argv[]) {
  1113. if(argc == 2 && !strncmp("-v", argv[1], 3))
  1114. die("st-" VERSION ", © 2009 st engineers\n");
  1115. else if(argc != 1)
  1116. die("usage: st [-v]\n");
  1117. setlocale(LC_CTYPE, "");
  1118. tnew(80, 24);
  1119. ttynew();
  1120. xinit();
  1121. run();
  1122. return 0;
  1123. }