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.

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