st.c 37 KB

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