st.c 38 KB

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