st.c 36 KB

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