st.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  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 int 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.c.y);
  790. if(term.c.y < term.row-1)
  791. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  792. break;
  793. case 1: /* above */
  794. if(term.c.y > 1)
  795. tclearregion(0, 0, term.col-1, term.c.y-1);
  796. tclearregion(0, term.c.y, term.c.x, term.c.y);
  797. break;
  798. case 2: /* all */
  799. tclearregion(0, 0, term.col-1, term.row-1);
  800. break;
  801. default:
  802. goto unknown;
  803. }
  804. break;
  805. case 'K': /* EL -- Clear line */
  806. switch(escseq.arg[0]) {
  807. case 0: /* right */
  808. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  809. break;
  810. case 1: /* left */
  811. tclearregion(0, term.c.y, term.c.x, term.c.y);
  812. break;
  813. case 2: /* all */
  814. tclearregion(0, term.c.y, term.col-1, term.c.y);
  815. break;
  816. }
  817. break;
  818. case 'S': /* SU -- Scroll <n> line up */
  819. DEFAULT(escseq.arg[0], 1);
  820. tscrollup(term.top, escseq.arg[0]);
  821. break;
  822. case 'T': /* SD -- Scroll <n> line down */
  823. DEFAULT(escseq.arg[0], 1);
  824. tscrolldown(term.top, escseq.arg[0]);
  825. break;
  826. case 'L': /* IL -- Insert <n> blank lines */
  827. DEFAULT(escseq.arg[0], 1);
  828. tinsertblankline(escseq.arg[0]);
  829. break;
  830. case 'l': /* RM -- Reset Mode */
  831. if(escseq.priv) {
  832. switch(escseq.arg[0]) {
  833. case 1:
  834. term.mode &= ~MODE_APPKEYPAD;
  835. break;
  836. case 5: /* TODO: DECSCNM -- Remove reverse video */
  837. break;
  838. case 7:
  839. term.mode &= ~MODE_WRAP;
  840. break;
  841. case 12: /* att610 -- Stop blinking cursor (IGNORED) */
  842. break;
  843. case 20:
  844. term.mode &= ~MODE_CRLF;
  845. break;
  846. case 25:
  847. term.c.state |= CURSOR_HIDE;
  848. break;
  849. case 1049: /* = 1047 and 1048 */
  850. case 1047:
  851. if(IS_SET(MODE_ALTSCREEN)) {
  852. tclearregion(0, 0, term.col-1, term.row-1);
  853. tswapscreen();
  854. }
  855. if(escseq.arg[0] == 1047)
  856. break;
  857. case 1048:
  858. tcursor(CURSOR_LOAD);
  859. break;
  860. default:
  861. goto unknown;
  862. }
  863. } else {
  864. switch(escseq.arg[0]) {
  865. case 4:
  866. term.mode &= ~MODE_INSERT;
  867. break;
  868. default:
  869. goto unknown;
  870. }
  871. }
  872. break;
  873. case 'M': /* DL -- Delete <n> lines */
  874. DEFAULT(escseq.arg[0], 1);
  875. tdeleteline(escseq.arg[0]);
  876. break;
  877. case 'X': /* ECH -- Erase <n> char */
  878. DEFAULT(escseq.arg[0], 1);
  879. tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
  880. break;
  881. case 'P': /* DCH -- Delete <n> char */
  882. DEFAULT(escseq.arg[0], 1);
  883. tdeletechar(escseq.arg[0]);
  884. break;
  885. /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
  886. case 'd': /* VPA -- Move to <row> */
  887. DEFAULT(escseq.arg[0], 1);
  888. tmoveto(term.c.x, escseq.arg[0]-1);
  889. break;
  890. case 'h': /* SM -- Set terminal mode */
  891. if(escseq.priv) {
  892. switch(escseq.arg[0]) {
  893. case 1:
  894. term.mode |= MODE_APPKEYPAD;
  895. break;
  896. case 5: /* DECSCNM -- Reverve video */
  897. /* TODO: set REVERSE on the whole screen (f) */
  898. break;
  899. case 7:
  900. term.mode |= MODE_WRAP;
  901. break;
  902. case 20:
  903. term.mode |= MODE_CRLF;
  904. break;
  905. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  906. /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
  907. if(escseq.narg > 1 && escseq.arg[1] != 25)
  908. break;
  909. case 25:
  910. term.c.state &= ~CURSOR_HIDE;
  911. break;
  912. case 1049: /* = 1047 and 1048 */
  913. case 1047:
  914. if(IS_SET(MODE_ALTSCREEN))
  915. tclearregion(0, 0, term.col-1, term.row-1);
  916. else
  917. tswapscreen();
  918. if(escseq.arg[0] == 1047)
  919. break;
  920. case 1048:
  921. tcursor(CURSOR_SAVE);
  922. break;
  923. default: goto unknown;
  924. }
  925. } else {
  926. switch(escseq.arg[0]) {
  927. case 4:
  928. term.mode |= MODE_INSERT;
  929. break;
  930. default: goto unknown;
  931. }
  932. };
  933. break;
  934. case 'm': /* SGR -- Terminal attribute (color) */
  935. tsetattr(escseq.arg, escseq.narg);
  936. break;
  937. case 'r': /* DECSTBM -- Set Scrolling Region */
  938. if(escseq.priv)
  939. goto unknown;
  940. else {
  941. DEFAULT(escseq.arg[0], 1);
  942. DEFAULT(escseq.arg[1], term.row);
  943. tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
  944. tmoveto(0, 0);
  945. }
  946. break;
  947. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  948. tcursor(CURSOR_SAVE);
  949. break;
  950. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  951. tcursor(CURSOR_LOAD);
  952. break;
  953. }
  954. }
  955. void
  956. csidump(void) {
  957. int i;
  958. printf("ESC [ %s", escseq.priv ? "? " : "");
  959. if(escseq.narg)
  960. for(i = 0; i < escseq.narg; i++)
  961. printf("%d ", escseq.arg[i]);
  962. if(escseq.mode)
  963. putchar(escseq.mode);
  964. putchar('\n');
  965. }
  966. void
  967. csireset(void) {
  968. memset(&escseq, 0, sizeof(escseq));
  969. }
  970. void
  971. tputtab(void) {
  972. int space = TAB - term.c.x % TAB;
  973. tmoveto(term.c.x + space, term.c.y);
  974. }
  975. void
  976. tputc(char c) {
  977. if(term.esc & ESC_START) {
  978. if(term.esc & ESC_CSI) {
  979. escseq.buf[escseq.len++] = c;
  980. if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
  981. term.esc = 0;
  982. csiparse(), csihandle();
  983. }
  984. /* TODO: handle other OSC */
  985. } else if(term.esc & ESC_OSC) {
  986. if(c == ';') {
  987. term.titlelen = 0;
  988. term.esc = ESC_START | ESC_TITLE;
  989. }
  990. } else if(term.esc & ESC_TITLE) {
  991. if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
  992. term.esc = 0;
  993. term.title[term.titlelen] = '\0';
  994. XStoreName(xw.dis, xw.win, term.title);
  995. } else {
  996. term.title[term.titlelen++] = c;
  997. }
  998. } else if(term.esc & ESC_ALTCHARSET) {
  999. switch(c) {
  1000. case '0': /* Line drawing crap */
  1001. term.c.attr.mode |= ATTR_GFX;
  1002. break;
  1003. case 'B': /* Back to regular text */
  1004. term.c.attr.mode &= ~ATTR_GFX;
  1005. break;
  1006. default:
  1007. printf("esc unhandled charset: ESC ( %c\n", c);
  1008. }
  1009. term.esc = 0;
  1010. } else {
  1011. switch(c) {
  1012. case '[':
  1013. term.esc |= ESC_CSI;
  1014. break;
  1015. case ']':
  1016. term.esc |= ESC_OSC;
  1017. break;
  1018. case '(':
  1019. term.esc |= ESC_ALTCHARSET;
  1020. break;
  1021. case 'D': /* IND -- Linefeed */
  1022. if(term.c.y == term.bot)
  1023. tscrollup(term.top, 1);
  1024. else
  1025. tmoveto(term.c.x, term.c.y+1);
  1026. term.esc = 0;
  1027. break;
  1028. case 'E': /* NEL -- Next line */
  1029. tnewline(1); /* always go to first col */
  1030. term.esc = 0;
  1031. break;
  1032. case 'M': /* RI -- Reverse index */
  1033. if(term.c.y == term.top)
  1034. tscrolldown(term.top, 1);
  1035. else
  1036. tmoveto(term.c.x, term.c.y-1);
  1037. term.esc = 0;
  1038. break;
  1039. case 'c': /* RIS -- Reset to inital state */
  1040. treset();
  1041. term.esc = 0;
  1042. break;
  1043. case '=': /* DECPAM -- Application keypad */
  1044. term.mode |= MODE_APPKEYPAD;
  1045. term.esc = 0;
  1046. break;
  1047. case '>': /* DECPNM -- Normal keypad */
  1048. term.mode &= ~MODE_APPKEYPAD;
  1049. term.esc = 0;
  1050. break;
  1051. case '7': /* DECSC -- Save Cursor */
  1052. tcursor(CURSOR_SAVE);
  1053. term.esc = 0;
  1054. break;
  1055. case '8': /* DECRC -- Restore Cursor */
  1056. tcursor(CURSOR_LOAD);
  1057. term.esc = 0;
  1058. break;
  1059. default:
  1060. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
  1061. term.esc = 0;
  1062. }
  1063. }
  1064. } else {
  1065. switch(c) {
  1066. case '\t':
  1067. tputtab();
  1068. break;
  1069. case '\b':
  1070. tmoveto(term.c.x-1, term.c.y);
  1071. break;
  1072. case '\r':
  1073. tmoveto(0, term.c.y);
  1074. break;
  1075. case '\f':
  1076. case '\v':
  1077. case '\n':
  1078. /* go to first col if the mode is set */
  1079. tnewline(IS_SET(MODE_CRLF));
  1080. break;
  1081. case '\a':
  1082. if(!(xw.state & WIN_FOCUSED))
  1083. xseturgency(1);
  1084. break;
  1085. case '\033':
  1086. csireset();
  1087. term.esc = ESC_START;
  1088. break;
  1089. default:
  1090. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1091. tnewline(1); /* always go to first col */
  1092. tsetchar(c);
  1093. if(term.c.x+1 < term.col)
  1094. tmoveto(term.c.x+1, term.c.y);
  1095. else
  1096. term.c.state |= CURSOR_WRAPNEXT;
  1097. break;
  1098. }
  1099. }
  1100. }
  1101. void
  1102. tputs(char *s, int len) {
  1103. for(; len > 0; len--)
  1104. tputc(*s++);
  1105. }
  1106. int
  1107. tresize(int col, int row) {
  1108. int i, x;
  1109. int minrow = MIN(row, term.row);
  1110. int mincol = MIN(col, term.col);
  1111. int slide = term.c.y - row + 1;
  1112. if(col < 1 || row < 1)
  1113. return 0;
  1114. /* free unneeded rows */
  1115. i = 0;
  1116. if(slide > 0) {
  1117. /* slide screen to keep cursor where we expect it -
  1118. * tscrollup would work here, but we can optimize to
  1119. * memmove because we're freeing the earlier lines */
  1120. for(/* i = 0 */; i < slide; i++) {
  1121. free(term.line[i]);
  1122. free(term.alt[i]);
  1123. }
  1124. memmove(term.line, term.line + slide, row * sizeof(Line));
  1125. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1126. }
  1127. for(i += row; i < term.row; i++) {
  1128. free(term.line[i]);
  1129. free(term.alt[i]);
  1130. }
  1131. /* resize to new height */
  1132. term.line = realloc(term.line, row * sizeof(Line));
  1133. term.alt = realloc(term.alt, row * sizeof(Line));
  1134. /* resize each row to new width, zero-pad if needed */
  1135. for(i = 0; i < minrow; i++) {
  1136. term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
  1137. term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
  1138. for(x = mincol; x < col; x++) {
  1139. term.line[i][x].state = 0;
  1140. term.alt[i][x].state = 0;
  1141. }
  1142. }
  1143. /* allocate any new rows */
  1144. for(/* i == minrow */; i < row; i++) {
  1145. term.line[i] = calloc(col, sizeof(Glyph));
  1146. term.alt [i] = calloc(col, sizeof(Glyph));
  1147. }
  1148. /* update terminal size */
  1149. term.col = col, term.row = row;
  1150. /* make use of the LIMIT in tmoveto */
  1151. tmoveto(term.c.x, term.c.y);
  1152. /* reset scrolling region */
  1153. tsetscroll(0, row-1);
  1154. return (slide > 0);
  1155. }
  1156. void
  1157. xresize(int col, int row) {
  1158. Pixmap newbuf;
  1159. int oldw, oldh;
  1160. oldw = xw.bufw;
  1161. oldh = xw.bufh;
  1162. xw.bufw = MAX(1, col * xw.cw);
  1163. xw.bufh = MAX(1, row * xw.ch);
  1164. newbuf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
  1165. XCopyArea(xw.dis, xw.buf, newbuf, dc.gc, 0, 0, xw.bufw, xw.bufh, 0, 0);
  1166. XFreePixmap(xw.dis, xw.buf);
  1167. XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
  1168. if(xw.bufw > oldw)
  1169. XFillRectangle(xw.dis, newbuf, dc.gc, oldw, 0,
  1170. xw.bufw-oldw, MIN(xw.bufh, oldh));
  1171. else if(xw.bufw < oldw && (BORDER > 0 || xw.w > xw.bufw))
  1172. XClearArea(xw.dis, xw.win, BORDER+xw.bufw, BORDER,
  1173. xw.w-xw.bufh-BORDER, BORDER+MIN(xw.bufh, oldh),
  1174. False);
  1175. if(xw.bufh > oldh)
  1176. XFillRectangle(xw.dis, newbuf, dc.gc, 0, oldh,
  1177. xw.bufw, xw.bufh-oldh);
  1178. else if(xw.bufh < oldh && (BORDER > 0 || xw.h > xw.bufh))
  1179. XClearArea(xw.dis, xw.win, BORDER, BORDER+xw.bufh,
  1180. xw.w-2*BORDER, xw.h-xw.bufh-BORDER,
  1181. False);
  1182. xw.buf = newbuf;
  1183. }
  1184. void
  1185. xloadcols(void) {
  1186. int i, r, g, b;
  1187. XColor color;
  1188. unsigned long white = WhitePixel(xw.dis, xw.scr);
  1189. for(i = 0; i < 16; i++) {
  1190. if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
  1191. dc.col[i] = white;
  1192. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1193. } else
  1194. dc.col[i] = color.pixel;
  1195. }
  1196. /* same colors as xterm */
  1197. for(r = 0; r < 6; r++)
  1198. for(g = 0; g < 6; g++)
  1199. for(b = 0; b < 6; b++) {
  1200. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1201. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1202. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1203. if (!XAllocColor(xw.dis, xw.cmap, &color)) {
  1204. dc.col[i] = white;
  1205. fprintf(stderr, "Could not allocate color %d\n", i);
  1206. } else
  1207. dc.col[i] = color.pixel;
  1208. i++;
  1209. }
  1210. for(r = 0; r < 24; r++, i++) {
  1211. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1212. if (!XAllocColor(xw.dis, xw.cmap, &color)) {
  1213. dc.col[i] = white;
  1214. fprintf(stderr, "Could not allocate color %d\n", i);
  1215. } else
  1216. dc.col[i] = color.pixel;
  1217. }
  1218. }
  1219. void
  1220. xclear(int x1, int y1, int x2, int y2) {
  1221. XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
  1222. XFillRectangle(xw.dis, xw.buf, dc.gc,
  1223. x1 * xw.cw, y1 * xw.ch,
  1224. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1225. }
  1226. void
  1227. xhints(void)
  1228. {
  1229. XClassHint class = {TNAME, TNAME};
  1230. XWMHints wm = {.flags = InputHint, .input = 1};
  1231. XSizeHints size = {
  1232. .flags = PSize | PResizeInc | PBaseSize,
  1233. .height = xw.h,
  1234. .width = xw.w,
  1235. .height_inc = xw.ch,
  1236. .width_inc = xw.cw,
  1237. .base_height = 2*BORDER,
  1238. .base_width = 2*BORDER,
  1239. };
  1240. XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
  1241. }
  1242. void
  1243. xinit(void) {
  1244. XSetWindowAttributes attrs;
  1245. if(!(xw.dis = XOpenDisplay(NULL)))
  1246. die("Can't open display\n");
  1247. xw.scr = XDefaultScreen(xw.dis);
  1248. /* font */
  1249. if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
  1250. die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
  1251. /* XXX: Assuming same size for bold font */
  1252. xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
  1253. xw.ch = dc.font->ascent + dc.font->descent;
  1254. /* colors */
  1255. xw.cmap = XDefaultColormap(xw.dis, xw.scr);
  1256. xloadcols();
  1257. /* window - default size */
  1258. xw.bufh = 24 * xw.ch;
  1259. xw.bufw = 80 * xw.cw;
  1260. xw.h = xw.bufh + 2*BORDER;
  1261. xw.w = xw.bufw + 2*BORDER;
  1262. attrs.background_pixel = dc.col[DefaultBG];
  1263. attrs.border_pixel = dc.col[DefaultBG];
  1264. attrs.bit_gravity = NorthWestGravity;
  1265. attrs.event_mask = FocusChangeMask | KeyPressMask
  1266. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1267. | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
  1268. attrs.colormap = xw.cmap;
  1269. xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
  1270. xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
  1271. XDefaultVisual(xw.dis, xw.scr),
  1272. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1273. | CWColormap,
  1274. &attrs);
  1275. xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
  1276. /* input methods */
  1277. xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
  1278. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1279. | XIMStatusNothing, XNClientWindow, xw.win,
  1280. XNFocusWindow, xw.win, NULL);
  1281. /* gc */
  1282. dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
  1283. XMapWindow(xw.dis, xw.win);
  1284. xhints();
  1285. XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
  1286. XSync(xw.dis, 0);
  1287. }
  1288. void
  1289. xdraws(char *s, Glyph base, int x, int y, int len) {
  1290. unsigned long xfg, xbg;
  1291. int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
  1292. int i;
  1293. if(base.mode & ATTR_REVERSE)
  1294. xfg = dc.col[base.bg], xbg = dc.col[base.fg];
  1295. else
  1296. xfg = dc.col[base.fg], xbg = dc.col[base.bg];
  1297. XSetBackground(xw.dis, dc.gc, xbg);
  1298. XSetForeground(xw.dis, dc.gc, xfg);
  1299. if(base.mode & ATTR_GFX)
  1300. for(i = 0; i < len; i++) {
  1301. char c = gfx[(unsigned int)s[i] % 256];
  1302. if(c)
  1303. s[i] = c;
  1304. else if(s[i] > 0x5f)
  1305. s[i] -= 0x5f;
  1306. }
  1307. XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
  1308. XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
  1309. if(base.mode & ATTR_UNDERLINE)
  1310. XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1311. }
  1312. void
  1313. xdrawcursor(void) {
  1314. static int oldx = 0;
  1315. static int oldy = 0;
  1316. Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
  1317. LIMIT(oldx, 0, term.col-1);
  1318. LIMIT(oldy, 0, term.row-1);
  1319. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1320. g.c = term.line[term.c.y][term.c.x].c;
  1321. /* remove the old cursor */
  1322. if(term.line[oldy][oldx].state & GLYPH_SET)
  1323. xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
  1324. else
  1325. xclear(oldx, oldy, oldx, oldy);
  1326. /* draw the new one */
  1327. if(!(term.c.state & CURSOR_HIDE) && (xw.state & WIN_FOCUSED)) {
  1328. xdraws(&g.c, g, term.c.x, term.c.y, 1);
  1329. oldx = term.c.x, oldy = term.c.y;
  1330. }
  1331. }
  1332. #ifdef DEBUG
  1333. /* basic drawing routines */
  1334. void
  1335. xdrawc(int x, int y, Glyph g) {
  1336. XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
  1337. XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
  1338. XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
  1339. XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
  1340. XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
  1341. }
  1342. void
  1343. draw(int dummy) {
  1344. int x, y;
  1345. xclear(0, 0, term.col-1, term.row-1);
  1346. for(y = 0; y < term.row; y++)
  1347. for(x = 0; x < term.col; x++)
  1348. if(term.line[y][x].state & GLYPH_SET)
  1349. xdrawc(x, y, term.line[y][x]);
  1350. xdrawcursor();
  1351. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1352. XFlush(xw.dis);
  1353. }
  1354. #else
  1355. /* optimized drawing routine */
  1356. void
  1357. draw(int redraw_all) {
  1358. int i, x, y, ox;
  1359. Glyph base, new;
  1360. char buf[DRAW_BUF_SIZ];
  1361. if(!(xw.state & WIN_VISIBLE))
  1362. return;
  1363. xclear(0, 0, term.col-1, term.row-1);
  1364. for(y = 0; y < term.row; y++) {
  1365. base = term.line[y][0];
  1366. i = ox = 0;
  1367. for(x = 0; x < term.col; x++) {
  1368. new = term.line[y][x];
  1369. if(sel.bx!=-1 && new.c && selected(x, y))
  1370. new.mode ^= ATTR_REVERSE;
  1371. if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1372. i >= DRAW_BUF_SIZ)) {
  1373. xdraws(buf, base, ox, y, i);
  1374. i = 0;
  1375. }
  1376. if(new.state & GLYPH_SET) {
  1377. if(i == 0) {
  1378. ox = x;
  1379. base = new;
  1380. }
  1381. buf[i++] = new.c;
  1382. }
  1383. }
  1384. if(i > 0)
  1385. xdraws(buf, base, ox, y, i);
  1386. }
  1387. xdrawcursor();
  1388. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
  1389. }
  1390. #endif
  1391. void
  1392. expose(XEvent *ev) {
  1393. XExposeEvent *e = &ev->xexpose;
  1394. if(xw.state & WIN_REDRAW) {
  1395. if(!e->count) {
  1396. xw.state &= ~WIN_REDRAW;
  1397. draw(SCREEN_REDRAW);
  1398. }
  1399. } else
  1400. XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
  1401. e->width, e->height, e->x, e->y);
  1402. }
  1403. void
  1404. visibility(XEvent *ev) {
  1405. XVisibilityEvent *e = &ev->xvisibility;
  1406. if(e->state == VisibilityFullyObscured)
  1407. xw.state &= ~WIN_VISIBLE;
  1408. else if(!(xw.state & WIN_VISIBLE))
  1409. /* need a full redraw for next Expose, not just a buf copy */
  1410. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1411. }
  1412. void
  1413. unmap(XEvent *ev) {
  1414. xw.state &= ~WIN_VISIBLE;
  1415. }
  1416. void
  1417. xseturgency(int add) {
  1418. XWMHints *h = XGetWMHints(xw.dis, xw.win);
  1419. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1420. XSetWMHints(xw.dis, xw.win, h);
  1421. XFree(h);
  1422. }
  1423. void
  1424. focus(XEvent *ev) {
  1425. if(ev->type == FocusIn) {
  1426. xw.state |= WIN_FOCUSED;
  1427. xseturgency(0);
  1428. } else
  1429. xw.state &= ~WIN_FOCUSED;
  1430. draw(SCREEN_UPDATE);
  1431. }
  1432. char*
  1433. kmap(KeySym k) {
  1434. int i;
  1435. for(i = 0; i < LEN(key); i++)
  1436. if(key[i].k == k)
  1437. return (char*)key[i].s;
  1438. return NULL;
  1439. }
  1440. void
  1441. kpress(XEvent *ev) {
  1442. XKeyEvent *e = &ev->xkey;
  1443. KeySym ksym;
  1444. char buf[32];
  1445. char *customkey;
  1446. int len;
  1447. int meta;
  1448. int shift;
  1449. Status status;
  1450. meta = e->state & Mod1Mask;
  1451. shift = e->state & ShiftMask;
  1452. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  1453. /* 1. custom keys from config.h */
  1454. if((customkey = kmap(ksym)))
  1455. ttywrite(customkey, strlen(customkey));
  1456. /* 2. hardcoded (overrides X lookup) */
  1457. else
  1458. switch(ksym) {
  1459. case XK_Up:
  1460. case XK_Down:
  1461. case XK_Left:
  1462. case XK_Right:
  1463. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
  1464. ttywrite(buf, 3);
  1465. break;
  1466. case XK_Insert:
  1467. if(shift)
  1468. selpaste();
  1469. break;
  1470. case XK_Return:
  1471. if(IS_SET(MODE_CRLF))
  1472. ttywrite("\r\n", 2);
  1473. else
  1474. ttywrite("\r", 1);
  1475. break;
  1476. /* 3. X lookup */
  1477. default:
  1478. if(len > 0) {
  1479. buf[sizeof(buf)-1] = '\0';
  1480. if(meta && len == 1)
  1481. ttywrite("\033", 1);
  1482. ttywrite(buf, len);
  1483. } else /* 4. nothing to send */
  1484. fprintf(stderr, "errkey: %d\n", (int)ksym);
  1485. break;
  1486. }
  1487. }
  1488. void
  1489. resize(XEvent *e) {
  1490. int col, row;
  1491. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  1492. return;
  1493. xw.w = e->xconfigure.width;
  1494. xw.h = e->xconfigure.height;
  1495. col = (xw.w - 2*BORDER) / xw.cw;
  1496. row = (xw.h - 2*BORDER) / xw.ch;
  1497. if(col == term.col && row == term.row)
  1498. return;
  1499. if(tresize(col, row))
  1500. draw(SCREEN_REDRAW);
  1501. ttyresize(col, row);
  1502. xresize(col, row);
  1503. }
  1504. void
  1505. run(void) {
  1506. XEvent ev;
  1507. fd_set rfd;
  1508. int xfd = XConnectionNumber(xw.dis);
  1509. for(;;) {
  1510. FD_ZERO(&rfd);
  1511. FD_SET(cmdfd, &rfd);
  1512. FD_SET(xfd, &rfd);
  1513. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
  1514. if(errno == EINTR)
  1515. continue;
  1516. die("select failed: %s\n", SERRNO);
  1517. }
  1518. if(FD_ISSET(cmdfd, &rfd)) {
  1519. ttyread();
  1520. draw(SCREEN_UPDATE);
  1521. }
  1522. while(XPending(xw.dis)) {
  1523. XNextEvent(xw.dis, &ev);
  1524. if (XFilterEvent(&ev, xw.win))
  1525. continue;
  1526. if(handler[ev.type])
  1527. (handler[ev.type])(&ev);
  1528. }
  1529. }
  1530. }
  1531. int
  1532. main(int argc, char *argv[]) {
  1533. int i;
  1534. for(i = 1; i < argc; i++) {
  1535. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  1536. case 't':
  1537. if(++i < argc) opt_title = argv[i];
  1538. break;
  1539. case 'e':
  1540. if(++i < argc) opt_cmd = argv[i];
  1541. break;
  1542. case 'v':
  1543. default:
  1544. die(USAGE);
  1545. }
  1546. }
  1547. setlocale(LC_CTYPE, "");
  1548. tnew(80, 24);
  1549. ttynew();
  1550. xinit();
  1551. selinit();
  1552. run();
  1553. return 0;
  1554. }