st.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433
  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 <stdbool.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <signal.h>
  14. #include <sys/ioctl.h>
  15. #include <sys/select.h>
  16. #include <sys/stat.h>
  17. #include <sys/time.h>
  18. #include <sys/types.h>
  19. #include <sys/wait.h>
  20. #include <time.h>
  21. #include <unistd.h>
  22. #include <X11/Xatom.h>
  23. #include <X11/Xlib.h>
  24. #include <X11/Xutil.h>
  25. #include <X11/cursorfont.h>
  26. #include <X11/keysym.h>
  27. #include <X11/extensions/Xdbe.h>
  28. #if defined(__linux)
  29. #include <pty.h>
  30. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  31. #include <util.h>
  32. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  33. #include <libutil.h>
  34. #endif
  35. #define USAGE \
  36. "st " VERSION " (c) 2010-2012 st engineers\n" \
  37. "usage: st [-t title] [-c class] [-g geometry]" \
  38. " [-w windowid] [-v] [-f file] [-e command...]\n"
  39. /* XEMBED messages */
  40. #define XEMBED_FOCUS_IN 4
  41. #define XEMBED_FOCUS_OUT 5
  42. /* Arbitrary sizes */
  43. #define ESC_BUF_SIZ 256
  44. #define ESC_ARG_SIZ 16
  45. #define STR_BUF_SIZ 256
  46. #define STR_ARG_SIZ 16
  47. #define DRAW_BUF_SIZ 1024
  48. #define UTF_SIZ 4
  49. #define XK_NO_MOD UINT_MAX
  50. #define XK_ANY_MOD 0
  51. #define SELECT_TIMEOUT (20*1000) /* 20 ms */
  52. #define DRAW_TIMEOUT (20*1000) /* 20 ms */
  53. #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
  54. #define SERRNO strerror(errno)
  55. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  56. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  57. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  58. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  59. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  60. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  61. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  62. #define IS_SET(flag) (term.mode & (flag))
  63. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
  64. #define X2COL(x) (((x) - BORDER)/xw.cw)
  65. #define Y2ROW(y) (((y) - BORDER)/xw.ch)
  66. enum glyph_attribute {
  67. ATTR_NULL = 0,
  68. ATTR_REVERSE = 1,
  69. ATTR_UNDERLINE = 2,
  70. ATTR_BOLD = 4,
  71. ATTR_GFX = 8,
  72. ATTR_ITALIC = 16,
  73. ATTR_BLINK = 32,
  74. };
  75. enum cursor_movement {
  76. CURSOR_UP,
  77. CURSOR_DOWN,
  78. CURSOR_LEFT,
  79. CURSOR_RIGHT,
  80. CURSOR_SAVE,
  81. CURSOR_LOAD
  82. };
  83. enum cursor_state {
  84. CURSOR_DEFAULT = 0,
  85. CURSOR_HIDE = 1,
  86. CURSOR_WRAPNEXT = 2
  87. };
  88. enum glyph_state {
  89. GLYPH_SET = 1,
  90. GLYPH_DIRTY = 2
  91. };
  92. enum term_mode {
  93. MODE_WRAP = 1,
  94. MODE_INSERT = 2,
  95. MODE_APPKEYPAD = 4,
  96. MODE_ALTSCREEN = 8,
  97. MODE_CRLF = 16,
  98. MODE_MOUSEBTN = 32,
  99. MODE_MOUSEMOTION = 64,
  100. MODE_MOUSE = 32|64,
  101. MODE_REVERSE = 128
  102. };
  103. enum escape_state {
  104. ESC_START = 1,
  105. ESC_CSI = 2,
  106. ESC_STR = 4, /* DSC, OSC, PM, APC */
  107. ESC_ALTCHARSET = 8,
  108. ESC_STR_END = 16, /* a final string was encountered */
  109. };
  110. enum window_state {
  111. WIN_VISIBLE = 1,
  112. WIN_REDRAW = 2,
  113. WIN_FOCUSED = 4
  114. };
  115. /* bit macro */
  116. #undef B0
  117. enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
  118. typedef unsigned char uchar;
  119. typedef unsigned int uint;
  120. typedef unsigned long ulong;
  121. typedef unsigned short ushort;
  122. typedef struct {
  123. char c[UTF_SIZ]; /* character code */
  124. uchar mode; /* attribute flags */
  125. ushort fg; /* foreground */
  126. ushort bg; /* background */
  127. uchar state; /* state flags */
  128. } Glyph;
  129. typedef Glyph* Line;
  130. typedef struct {
  131. Glyph attr; /* current char attributes */
  132. int x;
  133. int y;
  134. char state;
  135. } TCursor;
  136. /* CSI Escape sequence structs */
  137. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  138. typedef struct {
  139. char buf[ESC_BUF_SIZ]; /* raw string */
  140. int len; /* raw string length */
  141. char priv;
  142. int arg[ESC_ARG_SIZ];
  143. int narg; /* nb of args */
  144. char mode;
  145. } CSIEscape;
  146. /* STR Escape sequence structs */
  147. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  148. typedef struct {
  149. char type; /* ESC type ... */
  150. char buf[STR_BUF_SIZ]; /* raw string */
  151. int len; /* raw string length */
  152. char *args[STR_ARG_SIZ];
  153. int narg; /* nb of args */
  154. } STREscape;
  155. /* Internal representation of the screen */
  156. typedef struct {
  157. int row; /* nb row */
  158. int col; /* nb col */
  159. Line* line; /* screen */
  160. Line* alt; /* alternate screen */
  161. bool* dirty; /* dirtyness of lines */
  162. TCursor c; /* cursor */
  163. int top; /* top scroll limit */
  164. int bot; /* bottom scroll limit */
  165. int mode; /* terminal mode flags */
  166. int esc; /* escape state flags */
  167. bool *tabs;
  168. } Term;
  169. /* Purely graphic info */
  170. typedef struct {
  171. Display* dpy;
  172. Colormap cmap;
  173. Window win;
  174. XdbeBackBuffer buf;
  175. Atom xembed;
  176. XIM xim;
  177. XIC xic;
  178. int scr;
  179. Bool isfixed; /* is fixed geometry? */
  180. int fx, fy, fw, fh; /* fixed geometry */
  181. int w; /* window width */
  182. int h; /* window height */
  183. int ch; /* char height */
  184. int cw; /* char width */
  185. char state; /* focus, redraw, visible */
  186. struct timeval lastdraw;
  187. } XWindow;
  188. typedef struct {
  189. KeySym k;
  190. uint mask;
  191. char s[ESC_BUF_SIZ];
  192. } Key;
  193. /* TODO: use better name for vars... */
  194. typedef struct {
  195. int mode;
  196. int bx, by;
  197. int ex, ey;
  198. struct {int x, y;} b, e;
  199. char *clip;
  200. Atom xtarget;
  201. bool alt;
  202. struct timeval tclick1;
  203. struct timeval tclick2;
  204. } Selection;
  205. #include "config.h"
  206. /* Drawing Context */
  207. typedef struct {
  208. ulong col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
  209. GC gc;
  210. struct {
  211. int ascent;
  212. int descent;
  213. short lbearing;
  214. short rbearing;
  215. XFontSet set;
  216. } font, bfont, ifont;
  217. } DC;
  218. static void die(const char*, ...);
  219. static void draw(void);
  220. static void redraw(void);
  221. static void drawregion(int, int, int, int);
  222. static void execsh(void);
  223. static void sigchld(int);
  224. static void run(void);
  225. static bool last_draw_too_old(void);
  226. static void csidump(void);
  227. static void csihandle(void);
  228. static void csiparse(void);
  229. static void csireset(void);
  230. static void strdump(void);
  231. static void strhandle(void);
  232. static void strparse(void);
  233. static void strreset(void);
  234. static void tclearregion(int, int, int, int);
  235. static void tcursor(int);
  236. static void tdeletechar(int);
  237. static void tdeleteline(int);
  238. static void tinsertblank(int);
  239. static void tinsertblankline(int);
  240. static void tmoveto(int, int);
  241. static void tnew(int, int);
  242. static void tnewline(int);
  243. static void tputtab(bool);
  244. static void tputc(char*);
  245. static void treset(void);
  246. static int tresize(int, int);
  247. static void tscrollup(int, int);
  248. static void tscrolldown(int, int);
  249. static void tsetattr(int*, int);
  250. static void tsetchar(char*);
  251. static void tsetscroll(int, int);
  252. static void tswapscreen(void);
  253. static void tsetdirt(int, int);
  254. static void tsetmode(bool, bool, int *, int);
  255. static void tfulldirt(void);
  256. static void ttynew(void);
  257. static void ttyread(void);
  258. static void ttyresize(int, int);
  259. static void ttywrite(const char *, size_t);
  260. static void xdraws(char *, Glyph, int, int, int, int);
  261. static void xhints(void);
  262. static void xclear(int, int, int, int);
  263. static void xcopy(void);
  264. static void xdrawcursor(void);
  265. static void xinit(void);
  266. static void xloadcols(void);
  267. static void xseturgency(int);
  268. static void xsetsel(char*);
  269. static void xresize(int, int);
  270. static void expose(XEvent *);
  271. static void visibility(XEvent *);
  272. static void unmap(XEvent *);
  273. static char* kmap(KeySym, uint);
  274. static void kpress(XEvent *);
  275. static void cmessage(XEvent *);
  276. static void resize(XEvent *);
  277. static void focus(XEvent *);
  278. static void brelease(XEvent *);
  279. static void bpress(XEvent *);
  280. static void bmotion(XEvent *);
  281. static void selnotify(XEvent *);
  282. static void selclear(XEvent *);
  283. static void selrequest(XEvent *);
  284. static void selinit(void);
  285. static inline bool selected(int, int);
  286. static void selcopy(void);
  287. static void selpaste(void);
  288. static void selscroll(int, int);
  289. static int utf8decode(char *, long *);
  290. static int utf8encode(long *, char *);
  291. static int utf8size(char *);
  292. static int isfullutf8(char *, int);
  293. static void *xmalloc(size_t);
  294. static void *xrealloc(void *, size_t);
  295. static void (*handler[LASTEvent])(XEvent *) = {
  296. [KeyPress] = kpress,
  297. [ClientMessage] = cmessage,
  298. [ConfigureNotify] = resize,
  299. [VisibilityNotify] = visibility,
  300. [UnmapNotify] = unmap,
  301. [Expose] = expose,
  302. [FocusIn] = focus,
  303. [FocusOut] = focus,
  304. [MotionNotify] = bmotion,
  305. [ButtonPress] = bpress,
  306. [ButtonRelease] = brelease,
  307. [SelectionClear] = selclear,
  308. [SelectionNotify] = selnotify,
  309. [SelectionRequest] = selrequest,
  310. };
  311. /* Globals */
  312. static DC dc;
  313. static XWindow xw;
  314. static Term term;
  315. static CSIEscape csiescseq;
  316. static STREscape strescseq;
  317. static int cmdfd;
  318. static pid_t pid;
  319. static Selection sel;
  320. static FILE *fileio;
  321. static char **opt_cmd = NULL;
  322. static char *opt_io = NULL;
  323. static char *opt_title = NULL;
  324. static char *opt_embed = NULL;
  325. static char *opt_class = NULL;
  326. void *
  327. xmalloc(size_t len) {
  328. void *p = malloc(len);
  329. if(!p)
  330. die("Out of memory");
  331. return p;
  332. }
  333. void *
  334. xrealloc(void *p, size_t len) {
  335. if((p = realloc(p, len)) == NULL)
  336. die("Out of memory");
  337. return p;
  338. }
  339. int
  340. utf8decode(char *s, long *u) {
  341. uchar c;
  342. int i, n, rtn;
  343. rtn = 1;
  344. c = *s;
  345. if(~c & B7) { /* 0xxxxxxx */
  346. *u = c;
  347. return rtn;
  348. } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
  349. *u = c&(B4|B3|B2|B1|B0);
  350. n = 1;
  351. } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
  352. *u = c&(B3|B2|B1|B0);
  353. n = 2;
  354. } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
  355. *u = c & (B2|B1|B0);
  356. n = 3;
  357. } else
  358. goto invalid;
  359. for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
  360. c = *s;
  361. if((c & (B7|B6)) != B7) /* 10xxxxxx */
  362. goto invalid;
  363. *u <<= 6;
  364. *u |= c & (B5|B4|B3|B2|B1|B0);
  365. }
  366. if((n == 1 && *u < 0x80) ||
  367. (n == 2 && *u < 0x800) ||
  368. (n == 3 && *u < 0x10000) ||
  369. (*u >= 0xD800 && *u <= 0xDFFF))
  370. goto invalid;
  371. return rtn;
  372. invalid:
  373. *u = 0xFFFD;
  374. return rtn;
  375. }
  376. int
  377. utf8encode(long *u, char *s) {
  378. uchar *sp;
  379. ulong uc;
  380. int i, n;
  381. sp = (uchar*) s;
  382. uc = *u;
  383. if(uc < 0x80) {
  384. *sp = uc; /* 0xxxxxxx */
  385. return 1;
  386. } else if(*u < 0x800) {
  387. *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
  388. n = 1;
  389. } else if(uc < 0x10000) {
  390. *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
  391. n = 2;
  392. } else if(uc <= 0x10FFFF) {
  393. *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
  394. n = 3;
  395. } else {
  396. goto invalid;
  397. }
  398. for(i=n,++sp; i>0; --i,++sp)
  399. *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
  400. return n+1;
  401. invalid:
  402. /* U+FFFD */
  403. *s++ = '\xEF';
  404. *s++ = '\xBF';
  405. *s = '\xBD';
  406. return 3;
  407. }
  408. /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
  409. UTF-8 otherwise return 0 */
  410. int
  411. isfullutf8(char *s, int b) {
  412. uchar *c1, *c2, *c3;
  413. c1 = (uchar *) s;
  414. c2 = (uchar *) ++s;
  415. c3 = (uchar *) ++s;
  416. if(b < 1)
  417. return 0;
  418. else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
  419. return 0;
  420. else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
  421. ((b == 1) ||
  422. ((b == 2) && (*c2&(B7|B6)) == B7)))
  423. return 0;
  424. else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
  425. ((b == 1) ||
  426. ((b == 2) && (*c2&(B7|B6)) == B7) ||
  427. ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
  428. return 0;
  429. else
  430. return 1;
  431. }
  432. int
  433. utf8size(char *s) {
  434. uchar c = *s;
  435. if(~c&B7)
  436. return 1;
  437. else if((c&(B7|B6|B5)) == (B7|B6))
  438. return 2;
  439. else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
  440. return 3;
  441. else
  442. return 4;
  443. }
  444. void
  445. selinit(void) {
  446. memset(&sel.tclick1, 0, sizeof(sel.tclick1));
  447. memset(&sel.tclick2, 0, sizeof(sel.tclick2));
  448. sel.mode = 0;
  449. sel.bx = -1;
  450. sel.clip = NULL;
  451. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  452. if(sel.xtarget == None)
  453. sel.xtarget = XA_STRING;
  454. }
  455. static inline bool
  456. selected(int x, int y) {
  457. if(sel.ey == y && sel.by == y) {
  458. int bx = MIN(sel.bx, sel.ex);
  459. int ex = MAX(sel.bx, sel.ex);
  460. return BETWEEN(x, bx, ex);
  461. }
  462. return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
  463. || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
  464. }
  465. void
  466. getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
  467. if(b)
  468. *b = e->xbutton.button;
  469. *x = X2COL(e->xbutton.x);
  470. *y = Y2ROW(e->xbutton.y);
  471. sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
  472. sel.b.y = MIN(sel.by, sel.ey);
  473. sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
  474. sel.e.y = MAX(sel.by, sel.ey);
  475. }
  476. void
  477. mousereport(XEvent *e) {
  478. int x = X2COL(e->xbutton.x);
  479. int y = Y2ROW(e->xbutton.y);
  480. int button = e->xbutton.button;
  481. int state = e->xbutton.state;
  482. char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
  483. static int ob, ox, oy;
  484. /* from urxvt */
  485. if(e->xbutton.type == MotionNotify) {
  486. if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
  487. return;
  488. button = ob + 32;
  489. ox = x, oy = y;
  490. } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
  491. button = 3;
  492. } else {
  493. button -= Button1;
  494. if(button >= 3)
  495. button += 64 - 3;
  496. if(e->xbutton.type == ButtonPress) {
  497. ob = button;
  498. ox = x, oy = y;
  499. }
  500. }
  501. buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
  502. + (state & Mod4Mask ? 8 : 0)
  503. + (state & ControlMask ? 16 : 0);
  504. ttywrite(buf, sizeof(buf));
  505. }
  506. void
  507. bpress(XEvent *e) {
  508. if(IS_SET(MODE_MOUSE))
  509. mousereport(e);
  510. else if(e->xbutton.button == Button1) {
  511. if(sel.bx != -1)
  512. tsetdirt(sel.b.y, sel.e.y);
  513. sel.mode = 1;
  514. sel.ex = sel.bx = X2COL(e->xbutton.x);
  515. sel.ey = sel.by = Y2ROW(e->xbutton.y);
  516. }
  517. }
  518. void
  519. selcopy(void) {
  520. char *str, *ptr;
  521. int x, y, bufsize, is_selected = 0;
  522. if(sel.bx == -1)
  523. str = NULL;
  524. else {
  525. bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
  526. ptr = str = xmalloc(bufsize);
  527. /* append every set & selected glyph to the selection */
  528. for(y = 0; y < term.row; y++) {
  529. for(x = 0; x < term.col; x++) {
  530. is_selected = selected(x, y);
  531. if((term.line[y][x].state & GLYPH_SET) && is_selected) {
  532. int size = utf8size(term.line[y][x].c);
  533. memcpy(ptr, term.line[y][x].c, size);
  534. ptr += size;
  535. }
  536. }
  537. /* \n at the end of every selected line except for the last one */
  538. if(is_selected && y < sel.e.y)
  539. *ptr++ = '\n';
  540. }
  541. *ptr = 0;
  542. }
  543. sel.alt = IS_SET(MODE_ALTSCREEN);
  544. xsetsel(str);
  545. }
  546. void
  547. selnotify(XEvent *e) {
  548. ulong nitems, ofs, rem;
  549. int format;
  550. uchar *data;
  551. Atom type;
  552. ofs = 0;
  553. do {
  554. if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
  555. False, AnyPropertyType, &type, &format,
  556. &nitems, &rem, &data)) {
  557. fprintf(stderr, "Clipboard allocation failed\n");
  558. return;
  559. }
  560. ttywrite((const char *) data, nitems * format / 8);
  561. XFree(data);
  562. /* number of 32-bit chunks returned */
  563. ofs += nitems * format / 32;
  564. } while(rem > 0);
  565. }
  566. void
  567. selpaste() {
  568. XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
  569. }
  570. void selclear(XEvent *e) {
  571. if(sel.bx == -1)
  572. return;
  573. sel.bx = -1;
  574. tsetdirt(sel.b.y, sel.e.y);
  575. draw();
  576. }
  577. void
  578. selrequest(XEvent *e) {
  579. XSelectionRequestEvent *xsre;
  580. XSelectionEvent xev;
  581. Atom xa_targets;
  582. xsre = (XSelectionRequestEvent *) e;
  583. xev.type = SelectionNotify;
  584. xev.requestor = xsre->requestor;
  585. xev.selection = xsre->selection;
  586. xev.target = xsre->target;
  587. xev.time = xsre->time;
  588. /* reject */
  589. xev.property = None;
  590. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  591. if(xsre->target == xa_targets) {
  592. /* respond with the supported type */
  593. Atom string = sel.xtarget;
  594. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  595. XA_ATOM, 32, PropModeReplace,
  596. (uchar *) &string, 1);
  597. xev.property = xsre->property;
  598. } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
  599. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  600. xsre->target, 8, PropModeReplace,
  601. (uchar *) sel.clip, strlen(sel.clip));
  602. xev.property = xsre->property;
  603. }
  604. /* all done, send a notification to the listener */
  605. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  606. fprintf(stderr, "Error sending SelectionNotify event\n");
  607. }
  608. void
  609. xsetsel(char *str) {
  610. /* register the selection for both the clipboard and the primary */
  611. Atom clipboard;
  612. free(sel.clip);
  613. sel.clip = str;
  614. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
  615. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  616. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  617. XFlush(xw.dpy);
  618. }
  619. void
  620. brelease(XEvent *e) {
  621. if(IS_SET(MODE_MOUSE)) {
  622. mousereport(e);
  623. return;
  624. }
  625. if(e->xbutton.button == Button2)
  626. selpaste();
  627. else if(e->xbutton.button == Button1) {
  628. sel.mode = 0;
  629. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  630. term.dirty[sel.ey] = 1;
  631. if(sel.bx == sel.ex && sel.by == sel.ey) {
  632. struct timeval now;
  633. sel.bx = -1;
  634. gettimeofday(&now, NULL);
  635. if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
  636. /* triple click on the line */
  637. sel.b.x = sel.bx = 0;
  638. sel.e.x = sel.ex = term.col;
  639. sel.b.y = sel.e.y = sel.ey;
  640. selcopy();
  641. } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
  642. /* double click to select word */
  643. sel.bx = sel.ex;
  644. while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
  645. term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
  646. sel.b.x = sel.bx;
  647. while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
  648. term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
  649. sel.e.x = sel.ex;
  650. sel.b.y = sel.e.y = sel.ey;
  651. selcopy();
  652. }
  653. } else
  654. selcopy();
  655. }
  656. memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
  657. gettimeofday(&sel.tclick1, NULL);
  658. draw();
  659. }
  660. void
  661. bmotion(XEvent *e) {
  662. if(IS_SET(MODE_MOUSE)) {
  663. mousereport(e);
  664. return;
  665. }
  666. if(sel.mode) {
  667. int oldey = sel.ey, oldex = sel.ex;
  668. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  669. if(oldey != sel.ey || oldex != sel.ex) {
  670. int starty = MIN(oldey, sel.ey);
  671. int endy = MAX(oldey, sel.ey);
  672. tsetdirt(starty, endy);
  673. draw();
  674. }
  675. }
  676. }
  677. void
  678. die(const char *errstr, ...) {
  679. va_list ap;
  680. va_start(ap, errstr);
  681. vfprintf(stderr, errstr, ap);
  682. va_end(ap);
  683. exit(EXIT_FAILURE);
  684. }
  685. void
  686. execsh(void) {
  687. char **args;
  688. char *envshell = getenv("SHELL");
  689. unsetenv("COLUMNS");
  690. unsetenv("LINES");
  691. unsetenv("TERMCAP");
  692. DEFAULT(envshell, SHELL);
  693. putenv("TERM="TNAME);
  694. args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
  695. execvp(args[0], args);
  696. exit(EXIT_FAILURE);
  697. }
  698. void
  699. sigchld(int a) {
  700. int stat = 0;
  701. if(waitpid(pid, &stat, 0) < 0)
  702. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  703. if(WIFEXITED(stat))
  704. exit(WEXITSTATUS(stat));
  705. else
  706. exit(EXIT_FAILURE);
  707. }
  708. void
  709. ttynew(void) {
  710. int m, s;
  711. /* seems to work fine on linux, openbsd and freebsd */
  712. struct winsize w = {term.row, term.col, 0, 0};
  713. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  714. die("openpty failed: %s\n", SERRNO);
  715. switch(pid = fork()) {
  716. case -1:
  717. die("fork failed\n");
  718. break;
  719. case 0:
  720. setsid(); /* create a new process group */
  721. dup2(s, STDIN_FILENO);
  722. dup2(s, STDOUT_FILENO);
  723. dup2(s, STDERR_FILENO);
  724. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  725. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  726. close(s);
  727. close(m);
  728. execsh();
  729. break;
  730. default:
  731. close(s);
  732. cmdfd = m;
  733. signal(SIGCHLD, sigchld);
  734. if(opt_io) {
  735. if(!strcmp(opt_io, "-")) {
  736. fileio = stdout;
  737. } else {
  738. if(!(fileio = fopen(opt_io, "w"))) {
  739. fprintf(stderr, "Error opening %s:%s\n",
  740. opt_io, strerror(errno));
  741. }
  742. }
  743. }
  744. }
  745. }
  746. void
  747. dump(char c) {
  748. static int col;
  749. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  750. if(++col % 10 == 0)
  751. fprintf(stderr, "\n");
  752. }
  753. void
  754. ttyread(void) {
  755. static char buf[BUFSIZ];
  756. static int buflen = 0;
  757. char *ptr;
  758. char s[UTF_SIZ];
  759. int charsize; /* size of utf8 char in bytes */
  760. long utf8c;
  761. int ret;
  762. /* append read bytes to unprocessed bytes */
  763. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  764. die("Couldn't read from shell: %s\n", SERRNO);
  765. /* process every complete utf8 char */
  766. buflen += ret;
  767. ptr = buf;
  768. while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
  769. charsize = utf8decode(ptr, &utf8c);
  770. utf8encode(&utf8c, s);
  771. tputc(s);
  772. ptr += charsize;
  773. buflen -= charsize;
  774. }
  775. /* keep any uncomplete utf8 char for the next call */
  776. memmove(buf, ptr, buflen);
  777. }
  778. void
  779. ttywrite(const char *s, size_t n) {
  780. if(write(cmdfd, s, n) == -1)
  781. die("write error on tty: %s\n", SERRNO);
  782. }
  783. void
  784. ttyresize(int x, int y) {
  785. struct winsize w;
  786. w.ws_row = term.row;
  787. w.ws_col = term.col;
  788. w.ws_xpixel = xw.w;
  789. w.ws_ypixel = xw.h;
  790. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  791. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  792. }
  793. void
  794. tsetdirt(int top, int bot)
  795. {
  796. int i;
  797. LIMIT(top, 0, term.row-1);
  798. LIMIT(bot, 0, term.row-1);
  799. for(i = top; i <= bot; i++)
  800. term.dirty[i] = 1;
  801. }
  802. void
  803. tfulldirt(void)
  804. {
  805. tsetdirt(0, term.row-1);
  806. }
  807. void
  808. tcursor(int mode) {
  809. static TCursor c;
  810. if(mode == CURSOR_SAVE)
  811. c = term.c;
  812. else if(mode == CURSOR_LOAD)
  813. term.c = c, tmoveto(c.x, c.y);
  814. }
  815. void
  816. treset(void) {
  817. unsigned i;
  818. term.c = (TCursor){{
  819. .mode = ATTR_NULL,
  820. .fg = DefaultFG,
  821. .bg = DefaultBG
  822. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  823. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  824. for(i = TAB; i < term.col; i += TAB)
  825. term.tabs[i] = 1;
  826. term.top = 0, term.bot = term.row - 1;
  827. term.mode = MODE_WRAP;
  828. tclearregion(0, 0, term.col-1, term.row-1);
  829. }
  830. void
  831. tnew(int col, int row) {
  832. /* set screen size */
  833. term.row = row, term.col = col;
  834. term.line = xmalloc(term.row * sizeof(Line));
  835. term.alt = xmalloc(term.row * sizeof(Line));
  836. term.dirty = xmalloc(term.row * sizeof(*term.dirty));
  837. term.tabs = xmalloc(term.col * sizeof(*term.tabs));
  838. for(row = 0; row < term.row; row++) {
  839. term.line[row] = xmalloc(term.col * sizeof(Glyph));
  840. term.alt [row] = xmalloc(term.col * sizeof(Glyph));
  841. term.dirty[row] = 0;
  842. }
  843. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  844. /* setup screen */
  845. treset();
  846. }
  847. void
  848. tswapscreen(void) {
  849. Line* tmp = term.line;
  850. term.line = term.alt;
  851. term.alt = tmp;
  852. term.mode ^= MODE_ALTSCREEN;
  853. tfulldirt();
  854. }
  855. void
  856. tscrolldown(int orig, int n) {
  857. int i;
  858. Line temp;
  859. LIMIT(n, 0, term.bot-orig+1);
  860. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  861. for(i = term.bot; i >= orig+n; i--) {
  862. temp = term.line[i];
  863. term.line[i] = term.line[i-n];
  864. term.line[i-n] = temp;
  865. term.dirty[i] = 1;
  866. term.dirty[i-n] = 1;
  867. }
  868. selscroll(orig, n);
  869. }
  870. void
  871. tscrollup(int orig, int n) {
  872. int i;
  873. Line temp;
  874. LIMIT(n, 0, term.bot-orig+1);
  875. tclearregion(0, orig, term.col-1, orig+n-1);
  876. for(i = orig; i <= term.bot-n; i++) {
  877. temp = term.line[i];
  878. term.line[i] = term.line[i+n];
  879. term.line[i+n] = temp;
  880. term.dirty[i] = 1;
  881. term.dirty[i+n] = 1;
  882. }
  883. selscroll(orig, -n);
  884. }
  885. void
  886. selscroll(int orig, int n) {
  887. if(sel.bx == -1)
  888. return;
  889. if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
  890. if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
  891. sel.bx = -1;
  892. return;
  893. }
  894. if(sel.by < term.top) {
  895. sel.by = term.top;
  896. sel.bx = 0;
  897. }
  898. if(sel.ey > term.bot) {
  899. sel.ey = term.bot;
  900. sel.ex = term.col;
  901. }
  902. sel.b.y = sel.by, sel.b.x = sel.bx;
  903. sel.e.y = sel.ey, sel.e.x = sel.ex;
  904. }
  905. }
  906. void
  907. tnewline(int first_col) {
  908. int y = term.c.y;
  909. if(y == term.bot)
  910. tscrollup(term.top, 1);
  911. else
  912. y++;
  913. tmoveto(first_col ? 0 : term.c.x, y);
  914. }
  915. void
  916. csiparse(void) {
  917. /* int noarg = 1; */
  918. char *p = csiescseq.buf;
  919. csiescseq.narg = 0;
  920. if(*p == '?')
  921. csiescseq.priv = 1, p++;
  922. while(p < csiescseq.buf+csiescseq.len) {
  923. while(isdigit(*p)) {
  924. csiescseq.arg[csiescseq.narg] *= 10;
  925. csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
  926. }
  927. if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
  928. csiescseq.narg++, p++;
  929. else {
  930. csiescseq.mode = *p;
  931. csiescseq.narg++;
  932. return;
  933. }
  934. }
  935. }
  936. void
  937. tmoveto(int x, int y) {
  938. LIMIT(x, 0, term.col-1);
  939. LIMIT(y, 0, term.row-1);
  940. term.c.state &= ~CURSOR_WRAPNEXT;
  941. term.c.x = x;
  942. term.c.y = y;
  943. }
  944. void
  945. tsetchar(char *c) {
  946. term.dirty[term.c.y] = 1;
  947. term.line[term.c.y][term.c.x] = term.c.attr;
  948. memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
  949. term.line[term.c.y][term.c.x].state |= GLYPH_SET;
  950. }
  951. void
  952. tclearregion(int x1, int y1, int x2, int y2) {
  953. int x, y, temp;
  954. if(x1 > x2)
  955. temp = x1, x1 = x2, x2 = temp;
  956. if(y1 > y2)
  957. temp = y1, y1 = y2, y2 = temp;
  958. LIMIT(x1, 0, term.col-1);
  959. LIMIT(x2, 0, term.col-1);
  960. LIMIT(y1, 0, term.row-1);
  961. LIMIT(y2, 0, term.row-1);
  962. for(y = y1; y <= y2; y++) {
  963. term.dirty[y] = 1;
  964. for(x = x1; x <= x2; x++)
  965. term.line[y][x].state = 0;
  966. }
  967. }
  968. void
  969. tdeletechar(int n) {
  970. int src = term.c.x + n;
  971. int dst = term.c.x;
  972. int size = term.col - src;
  973. term.dirty[term.c.y] = 1;
  974. if(src >= term.col) {
  975. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  976. return;
  977. }
  978. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  979. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  980. }
  981. void
  982. tinsertblank(int n) {
  983. int src = term.c.x;
  984. int dst = src + n;
  985. int size = term.col - dst;
  986. term.dirty[term.c.y] = 1;
  987. if(dst >= term.col) {
  988. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  989. return;
  990. }
  991. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
  992. tclearregion(src, term.c.y, dst - 1, term.c.y);
  993. }
  994. void
  995. tinsertblankline(int n) {
  996. if(term.c.y < term.top || term.c.y > term.bot)
  997. return;
  998. tscrolldown(term.c.y, n);
  999. }
  1000. void
  1001. tdeleteline(int n) {
  1002. if(term.c.y < term.top || term.c.y > term.bot)
  1003. return;
  1004. tscrollup(term.c.y, n);
  1005. }
  1006. void
  1007. tsetattr(int *attr, int l) {
  1008. int i;
  1009. for(i = 0; i < l; i++) {
  1010. switch(attr[i]) {
  1011. case 0:
  1012. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
  1013. | ATTR_ITALIC | ATTR_BLINK);
  1014. term.c.attr.fg = DefaultFG;
  1015. term.c.attr.bg = DefaultBG;
  1016. break;
  1017. case 1:
  1018. term.c.attr.mode |= ATTR_BOLD;
  1019. break;
  1020. case 3: /* enter standout (highlight) */
  1021. term.c.attr.mode |= ATTR_ITALIC;
  1022. break;
  1023. case 4:
  1024. term.c.attr.mode |= ATTR_UNDERLINE;
  1025. break;
  1026. case 5:
  1027. term.c.attr.mode |= ATTR_BLINK;
  1028. break;
  1029. case 7:
  1030. term.c.attr.mode |= ATTR_REVERSE;
  1031. break;
  1032. case 22:
  1033. term.c.attr.mode &= ~ATTR_BOLD;
  1034. break;
  1035. case 23: /* leave standout (highlight) mode */
  1036. term.c.attr.mode &= ~ATTR_ITALIC;
  1037. break;
  1038. case 24:
  1039. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1040. break;
  1041. case 25:
  1042. term.c.attr.mode &= ~ATTR_BLINK;
  1043. break;
  1044. case 27:
  1045. term.c.attr.mode &= ~ATTR_REVERSE;
  1046. break;
  1047. case 38:
  1048. if(i + 2 < l && attr[i + 1] == 5) {
  1049. i += 2;
  1050. if(BETWEEN(attr[i], 0, 255))
  1051. term.c.attr.fg = attr[i];
  1052. else
  1053. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
  1054. }
  1055. else
  1056. fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
  1057. break;
  1058. case 39:
  1059. term.c.attr.fg = DefaultFG;
  1060. break;
  1061. case 48:
  1062. if(i + 2 < l && attr[i + 1] == 5) {
  1063. i += 2;
  1064. if(BETWEEN(attr[i], 0, 255))
  1065. term.c.attr.bg = attr[i];
  1066. else
  1067. fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
  1068. }
  1069. else
  1070. fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
  1071. break;
  1072. case 49:
  1073. term.c.attr.bg = DefaultBG;
  1074. break;
  1075. default:
  1076. if(BETWEEN(attr[i], 30, 37))
  1077. term.c.attr.fg = attr[i] - 30;
  1078. else if(BETWEEN(attr[i], 40, 47))
  1079. term.c.attr.bg = attr[i] - 40;
  1080. else if(BETWEEN(attr[i], 90, 97))
  1081. term.c.attr.fg = attr[i] - 90 + 8;
  1082. else if(BETWEEN(attr[i], 100, 107))
  1083. term.c.attr.bg = attr[i] - 100 + 8;
  1084. else
  1085. fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
  1086. break;
  1087. }
  1088. }
  1089. }
  1090. void
  1091. tsetscroll(int t, int b) {
  1092. int temp;
  1093. LIMIT(t, 0, term.row-1);
  1094. LIMIT(b, 0, term.row-1);
  1095. if(t > b) {
  1096. temp = t;
  1097. t = b;
  1098. b = temp;
  1099. }
  1100. term.top = t;
  1101. term.bot = b;
  1102. }
  1103. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1104. void
  1105. tsetmode(bool priv, bool set, int *args, int narg) {
  1106. int *lim, mode;
  1107. for(lim = args + narg; args < lim; ++args) {
  1108. if(priv) {
  1109. switch(*args) {
  1110. case 1:
  1111. MODBIT(term.mode, set, MODE_APPKEYPAD);
  1112. break;
  1113. case 5: /* DECSCNM -- Reverve video */
  1114. mode = term.mode;
  1115. MODBIT(term.mode,set, MODE_REVERSE);
  1116. if(mode != term.mode)
  1117. redraw();
  1118. break;
  1119. case 7:
  1120. MODBIT(term.mode, set, MODE_WRAP);
  1121. break;
  1122. case 20:
  1123. MODBIT(term.mode, set, MODE_CRLF);
  1124. break;
  1125. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1126. break;
  1127. case 25:
  1128. MODBIT(term.c.state, !set, CURSOR_HIDE);
  1129. break;
  1130. case 1000: /* 1000,1002: enable xterm mouse report */
  1131. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1132. break;
  1133. case 1002:
  1134. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1135. break;
  1136. case 1049: /* = 1047 and 1048 */
  1137. case 47:
  1138. case 1047:
  1139. if(IS_SET(MODE_ALTSCREEN))
  1140. tclearregion(0, 0, term.col-1, term.row-1);
  1141. if((set && !IS_SET(MODE_ALTSCREEN)) ||
  1142. (!set && IS_SET(MODE_ALTSCREEN))) {
  1143. tswapscreen();
  1144. }
  1145. if(*args != 1049)
  1146. break;
  1147. /* pass through */
  1148. case 1048:
  1149. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1150. break;
  1151. default:
  1152. fprintf(stderr,
  1153. "erresc: unknown private set/reset mode %d\n",
  1154. *args);
  1155. break;
  1156. }
  1157. } else {
  1158. switch(*args) {
  1159. case 4:
  1160. MODBIT(term.mode, set, MODE_INSERT);
  1161. break;
  1162. default:
  1163. fprintf(stderr,
  1164. "erresc: unknown set/reset mode %d\n",
  1165. *args);
  1166. break;
  1167. }
  1168. }
  1169. }
  1170. }
  1171. #undef MODBIT
  1172. void
  1173. csihandle(void) {
  1174. switch(csiescseq.mode) {
  1175. default:
  1176. unknown:
  1177. fprintf(stderr, "erresc: unknown csi ");
  1178. csidump();
  1179. /* die(""); */
  1180. break;
  1181. case '@': /* ICH -- Insert <n> blank char */
  1182. DEFAULT(csiescseq.arg[0], 1);
  1183. tinsertblank(csiescseq.arg[0]);
  1184. break;
  1185. case 'A': /* CUU -- Cursor <n> Up */
  1186. case 'e':
  1187. DEFAULT(csiescseq.arg[0], 1);
  1188. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1189. break;
  1190. case 'B': /* CUD -- Cursor <n> Down */
  1191. DEFAULT(csiescseq.arg[0], 1);
  1192. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1193. break;
  1194. case 'C': /* CUF -- Cursor <n> Forward */
  1195. case 'a':
  1196. DEFAULT(csiescseq.arg[0], 1);
  1197. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1198. break;
  1199. case 'D': /* CUB -- Cursor <n> Backward */
  1200. DEFAULT(csiescseq.arg[0], 1);
  1201. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1202. break;
  1203. case 'E': /* CNL -- Cursor <n> Down and first col */
  1204. DEFAULT(csiescseq.arg[0], 1);
  1205. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1206. break;
  1207. case 'F': /* CPL -- Cursor <n> Up and first col */
  1208. DEFAULT(csiescseq.arg[0], 1);
  1209. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1210. break;
  1211. case 'g': /* TBC -- Tabulation clear */
  1212. switch (csiescseq.arg[0]) {
  1213. case 0: /* clear current tab stop */
  1214. term.tabs[term.c.x] = 0;
  1215. break;
  1216. case 3: /* clear all the tabs */
  1217. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1218. break;
  1219. default:
  1220. goto unknown;
  1221. }
  1222. break;
  1223. case 'G': /* CHA -- Move to <col> */
  1224. case '`': /* HPA */
  1225. DEFAULT(csiescseq.arg[0], 1);
  1226. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1227. break;
  1228. case 'H': /* CUP -- Move to <row> <col> */
  1229. case 'f': /* HVP */
  1230. DEFAULT(csiescseq.arg[0], 1);
  1231. DEFAULT(csiescseq.arg[1], 1);
  1232. tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1233. break;
  1234. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1235. DEFAULT(csiescseq.arg[0], 1);
  1236. while(csiescseq.arg[0]--)
  1237. tputtab(1);
  1238. break;
  1239. case 'J': /* ED -- Clear screen */
  1240. sel.bx = -1;
  1241. switch(csiescseq.arg[0]) {
  1242. case 0: /* below */
  1243. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1244. if(term.c.y < term.row-1)
  1245. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  1246. break;
  1247. case 1: /* above */
  1248. if(term.c.y > 1)
  1249. tclearregion(0, 0, term.col-1, term.c.y-1);
  1250. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1251. break;
  1252. case 2: /* all */
  1253. tclearregion(0, 0, term.col-1, term.row-1);
  1254. break;
  1255. default:
  1256. goto unknown;
  1257. }
  1258. break;
  1259. case 'K': /* EL -- Clear line */
  1260. switch(csiescseq.arg[0]) {
  1261. case 0: /* right */
  1262. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1263. break;
  1264. case 1: /* left */
  1265. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1266. break;
  1267. case 2: /* all */
  1268. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1269. break;
  1270. }
  1271. break;
  1272. case 'S': /* SU -- Scroll <n> line up */
  1273. DEFAULT(csiescseq.arg[0], 1);
  1274. tscrollup(term.top, csiescseq.arg[0]);
  1275. break;
  1276. case 'T': /* SD -- Scroll <n> line down */
  1277. DEFAULT(csiescseq.arg[0], 1);
  1278. tscrolldown(term.top, csiescseq.arg[0]);
  1279. break;
  1280. case 'L': /* IL -- Insert <n> blank lines */
  1281. DEFAULT(csiescseq.arg[0], 1);
  1282. tinsertblankline(csiescseq.arg[0]);
  1283. break;
  1284. case 'l': /* RM -- Reset Mode */
  1285. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1286. break;
  1287. case 'M': /* DL -- Delete <n> lines */
  1288. DEFAULT(csiescseq.arg[0], 1);
  1289. tdeleteline(csiescseq.arg[0]);
  1290. break;
  1291. case 'X': /* ECH -- Erase <n> char */
  1292. DEFAULT(csiescseq.arg[0], 1);
  1293. tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
  1294. break;
  1295. case 'P': /* DCH -- Delete <n> char */
  1296. DEFAULT(csiescseq.arg[0], 1);
  1297. tdeletechar(csiescseq.arg[0]);
  1298. break;
  1299. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1300. DEFAULT(csiescseq.arg[0], 1);
  1301. while(csiescseq.arg[0]--)
  1302. tputtab(0);
  1303. break;
  1304. case 'd': /* VPA -- Move to <row> */
  1305. DEFAULT(csiescseq.arg[0], 1);
  1306. tmoveto(term.c.x, csiescseq.arg[0]-1);
  1307. break;
  1308. case 'h': /* SM -- Set terminal mode */
  1309. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1310. break;
  1311. case 'm': /* SGR -- Terminal attribute (color) */
  1312. tsetattr(csiescseq.arg, csiescseq.narg);
  1313. break;
  1314. case 'r': /* DECSTBM -- Set Scrolling Region */
  1315. if(csiescseq.priv)
  1316. goto unknown;
  1317. else {
  1318. DEFAULT(csiescseq.arg[0], 1);
  1319. DEFAULT(csiescseq.arg[1], term.row);
  1320. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1321. tmoveto(0, 0);
  1322. }
  1323. break;
  1324. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1325. tcursor(CURSOR_SAVE);
  1326. break;
  1327. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1328. tcursor(CURSOR_LOAD);
  1329. break;
  1330. }
  1331. }
  1332. void
  1333. csidump(void) {
  1334. int i;
  1335. printf("ESC[");
  1336. for(i = 0; i < csiescseq.len; i++) {
  1337. uint c = csiescseq.buf[i] & 0xff;
  1338. if(isprint(c)) putchar(c);
  1339. else if(c == '\n') printf("(\\n)");
  1340. else if(c == '\r') printf("(\\r)");
  1341. else if(c == 0x1b) printf("(\\e)");
  1342. else printf("(%02x)", c);
  1343. }
  1344. putchar('\n');
  1345. }
  1346. void
  1347. csireset(void) {
  1348. memset(&csiescseq, 0, sizeof(csiescseq));
  1349. }
  1350. void
  1351. strhandle(void) {
  1352. char *p;
  1353. /*
  1354. * TODO: make this being useful in case of color palette change.
  1355. */
  1356. strparse();
  1357. p = strescseq.buf;
  1358. switch(strescseq.type) {
  1359. case ']': /* OSC -- Operating System Command */
  1360. switch(p[0]) {
  1361. case '0':
  1362. case '1':
  1363. case '2':
  1364. /*
  1365. * TODO: Handle special chars in string, like umlauts.
  1366. */
  1367. if(p[1] == ';') {
  1368. XStoreName(xw.dpy, xw.win, strescseq.buf+2);
  1369. }
  1370. break;
  1371. case ';':
  1372. XStoreName(xw.dpy, xw.win, strescseq.buf+1);
  1373. break;
  1374. case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
  1375. break;
  1376. default:
  1377. fprintf(stderr, "erresc: unknown str ");
  1378. strdump();
  1379. break;
  1380. }
  1381. break;
  1382. case 'k': /* old title set compatibility */
  1383. XStoreName(xw.dpy, xw.win, strescseq.buf);
  1384. break;
  1385. case 'P': /* DSC -- Device Control String */
  1386. case '_': /* APC -- Application Program Command */
  1387. case '^': /* PM -- Privacy Message */
  1388. default:
  1389. fprintf(stderr, "erresc: unknown str ");
  1390. strdump();
  1391. /* die(""); */
  1392. break;
  1393. }
  1394. }
  1395. void
  1396. strparse(void) {
  1397. /*
  1398. * TODO: Implement parsing like for CSI when required.
  1399. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1400. */
  1401. return;
  1402. }
  1403. void
  1404. strdump(void) {
  1405. int i;
  1406. printf("ESC%c", strescseq.type);
  1407. for(i = 0; i < strescseq.len; i++) {
  1408. uint c = strescseq.buf[i] & 0xff;
  1409. if(isprint(c)) putchar(c);
  1410. else if(c == '\n') printf("(\\n)");
  1411. else if(c == '\r') printf("(\\r)");
  1412. else if(c == 0x1b) printf("(\\e)");
  1413. else printf("(%02x)", c);
  1414. }
  1415. printf("ESC\\\n");
  1416. }
  1417. void
  1418. strreset(void) {
  1419. memset(&strescseq, 0, sizeof(strescseq));
  1420. }
  1421. void
  1422. tputtab(bool forward) {
  1423. unsigned x = term.c.x;
  1424. if(forward) {
  1425. if(x == term.col)
  1426. return;
  1427. for(++x; x < term.col && !term.tabs[x]; ++x)
  1428. /* nothing */ ;
  1429. } else {
  1430. if(x == 0)
  1431. return;
  1432. for(--x; x > 0 && !term.tabs[x]; --x)
  1433. /* nothing */ ;
  1434. }
  1435. tmoveto(x, term.c.y);
  1436. }
  1437. void
  1438. tputc(char *c) {
  1439. char ascii = *c;
  1440. if(fileio) {
  1441. putc(ascii, fileio);
  1442. fflush(fileio);
  1443. }
  1444. if(term.esc & ESC_START) {
  1445. if(term.esc & ESC_CSI) {
  1446. csiescseq.buf[csiescseq.len++] = ascii;
  1447. if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
  1448. term.esc = 0;
  1449. csiparse(), csihandle();
  1450. }
  1451. } else if(term.esc & ESC_STR) {
  1452. switch(ascii) {
  1453. case '\033':
  1454. term.esc = ESC_START | ESC_STR_END;
  1455. break;
  1456. case '\a': /* backwards compatibility to xterm */
  1457. term.esc = 0;
  1458. strhandle();
  1459. break;
  1460. default:
  1461. strescseq.buf[strescseq.len++] = ascii;
  1462. if(strescseq.len+1 >= STR_BUF_SIZ) {
  1463. term.esc = 0;
  1464. strhandle();
  1465. }
  1466. }
  1467. } else if(term.esc & ESC_STR_END) {
  1468. term.esc = 0;
  1469. if(ascii == '\\')
  1470. strhandle();
  1471. } else if(term.esc & ESC_ALTCHARSET) {
  1472. switch(ascii) {
  1473. case '0': /* Line drawing crap */
  1474. term.c.attr.mode |= ATTR_GFX;
  1475. break;
  1476. case 'B': /* Back to regular text */
  1477. term.c.attr.mode &= ~ATTR_GFX;
  1478. break;
  1479. default:
  1480. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1481. }
  1482. term.esc = 0;
  1483. } else {
  1484. switch(ascii) {
  1485. case '[':
  1486. term.esc |= ESC_CSI;
  1487. break;
  1488. case 'P': /* DCS -- Device Control String */
  1489. case '_': /* APC -- Application Program Command */
  1490. case '^': /* PM -- Privacy Message */
  1491. case ']': /* OSC -- Operating System Command */
  1492. case 'k': /* old title set compatibility */
  1493. strreset();
  1494. strescseq.type = ascii;
  1495. term.esc |= ESC_STR;
  1496. break;
  1497. case '(':
  1498. term.esc |= ESC_ALTCHARSET;
  1499. break;
  1500. case 'D': /* IND -- Linefeed */
  1501. if(term.c.y == term.bot)
  1502. tscrollup(term.top, 1);
  1503. else
  1504. tmoveto(term.c.x, term.c.y+1);
  1505. term.esc = 0;
  1506. break;
  1507. case 'E': /* NEL -- Next line */
  1508. tnewline(1); /* always go to first col */
  1509. term.esc = 0;
  1510. break;
  1511. case 'H': /* HTS -- Horizontal tab stop */
  1512. term.tabs[term.c.x] = 1;
  1513. term.esc = 0;
  1514. break;
  1515. case 'M': /* RI -- Reverse index */
  1516. if(term.c.y == term.top)
  1517. tscrolldown(term.top, 1);
  1518. else
  1519. tmoveto(term.c.x, term.c.y-1);
  1520. term.esc = 0;
  1521. break;
  1522. case 'c': /* RIS -- Reset to inital state */
  1523. treset();
  1524. term.esc = 0;
  1525. break;
  1526. case '=': /* DECPAM -- Application keypad */
  1527. term.mode |= MODE_APPKEYPAD;
  1528. term.esc = 0;
  1529. break;
  1530. case '>': /* DECPNM -- Normal keypad */
  1531. term.mode &= ~MODE_APPKEYPAD;
  1532. term.esc = 0;
  1533. break;
  1534. case '7': /* DECSC -- Save Cursor */
  1535. tcursor(CURSOR_SAVE);
  1536. term.esc = 0;
  1537. break;
  1538. case '8': /* DECRC -- Restore Cursor */
  1539. tcursor(CURSOR_LOAD);
  1540. term.esc = 0;
  1541. break;
  1542. case '\\': /* ST -- Stop */
  1543. term.esc = 0;
  1544. break;
  1545. default:
  1546. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1547. (uchar) ascii, isprint(ascii)?ascii:'.');
  1548. term.esc = 0;
  1549. }
  1550. }
  1551. } else {
  1552. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1553. sel.bx = -1;
  1554. switch(ascii) {
  1555. case '\t':
  1556. tputtab(1);
  1557. break;
  1558. case '\b':
  1559. tmoveto(term.c.x-1, term.c.y);
  1560. break;
  1561. case '\r':
  1562. tmoveto(0, term.c.y);
  1563. break;
  1564. case '\f':
  1565. case '\v':
  1566. case '\n':
  1567. /* go to first col if the mode is set */
  1568. tnewline(IS_SET(MODE_CRLF));
  1569. break;
  1570. case '\a':
  1571. if(!(xw.state & WIN_FOCUSED))
  1572. xseturgency(1);
  1573. break;
  1574. case '\033':
  1575. csireset();
  1576. term.esc = ESC_START;
  1577. break;
  1578. default:
  1579. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1580. tnewline(1); /* always go to first col */
  1581. tsetchar(c);
  1582. if(term.c.x+1 < term.col)
  1583. tmoveto(term.c.x+1, term.c.y);
  1584. else
  1585. term.c.state |= CURSOR_WRAPNEXT;
  1586. }
  1587. }
  1588. }
  1589. int
  1590. tresize(int col, int row) {
  1591. int i, x;
  1592. int minrow = MIN(row, term.row);
  1593. int mincol = MIN(col, term.col);
  1594. int slide = term.c.y - row + 1;
  1595. if(col < 1 || row < 1)
  1596. return 0;
  1597. /* free unneeded rows */
  1598. i = 0;
  1599. if(slide > 0) {
  1600. /* slide screen to keep cursor where we expect it -
  1601. * tscrollup would work here, but we can optimize to
  1602. * memmove because we're freeing the earlier lines */
  1603. for(/* i = 0 */; i < slide; i++) {
  1604. free(term.line[i]);
  1605. free(term.alt[i]);
  1606. }
  1607. memmove(term.line, term.line + slide, row * sizeof(Line));
  1608. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1609. }
  1610. for(i += row; i < term.row; i++) {
  1611. free(term.line[i]);
  1612. free(term.alt[i]);
  1613. }
  1614. /* resize to new height */
  1615. term.line = xrealloc(term.line, row * sizeof(Line));
  1616. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1617. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1618. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1619. /* resize each row to new width, zero-pad if needed */
  1620. for(i = 0; i < minrow; i++) {
  1621. term.dirty[i] = 1;
  1622. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1623. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1624. for(x = mincol; x < col; x++) {
  1625. term.line[i][x].state = 0;
  1626. term.alt[i][x].state = 0;
  1627. }
  1628. }
  1629. /* allocate any new rows */
  1630. for(/* i == minrow */; i < row; i++) {
  1631. term.dirty[i] = 1;
  1632. term.line[i] = calloc(col, sizeof(Glyph));
  1633. term.alt [i] = calloc(col, sizeof(Glyph));
  1634. }
  1635. if(col > term.col) {
  1636. bool *bp = term.tabs + term.col;
  1637. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1638. while(--bp > term.tabs && !*bp)
  1639. /* nothing */ ;
  1640. for(bp += TAB; bp < term.tabs + col; bp += TAB)
  1641. *bp = 1;
  1642. }
  1643. /* update terminal size */
  1644. term.col = col, term.row = row;
  1645. /* make use of the LIMIT in tmoveto */
  1646. tmoveto(term.c.x, term.c.y);
  1647. /* reset scrolling region */
  1648. tsetscroll(0, row-1);
  1649. return (slide > 0);
  1650. }
  1651. void
  1652. xresize(int col, int row) {
  1653. xw.w = MAX(1, 2*BORDER + col * xw.cw);
  1654. xw.h = MAX(1, 2*BORDER + row * xw.ch);
  1655. }
  1656. void
  1657. xloadcols(void) {
  1658. int i, r, g, b;
  1659. XColor color;
  1660. ulong white = WhitePixel(xw.dpy, xw.scr);
  1661. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1662. for(i = 0; i < LEN(colorname); i++) {
  1663. if(!colorname[i])
  1664. continue;
  1665. if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
  1666. dc.col[i] = white;
  1667. fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
  1668. } else
  1669. dc.col[i] = color.pixel;
  1670. }
  1671. /* load colors [16-255] ; same colors as xterm */
  1672. for(i = 16, r = 0; r < 6; r++)
  1673. for(g = 0; g < 6; g++)
  1674. for(b = 0; b < 6; b++) {
  1675. color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1676. color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1677. color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1678. if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1679. dc.col[i] = white;
  1680. fprintf(stderr, "Could not allocate color %d\n", i);
  1681. } else
  1682. dc.col[i] = color.pixel;
  1683. i++;
  1684. }
  1685. for(r = 0; r < 24; r++, i++) {
  1686. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  1687. if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
  1688. dc.col[i] = white;
  1689. fprintf(stderr, "Could not allocate color %d\n", i);
  1690. } else
  1691. dc.col[i] = color.pixel;
  1692. }
  1693. }
  1694. void
  1695. xclear(int x1, int y1, int x2, int y2) {
  1696. XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
  1697. XFillRectangle(xw.dpy, xw.buf, dc.gc,
  1698. BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
  1699. (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
  1700. }
  1701. void
  1702. xhints(void) {
  1703. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1704. XWMHints wm = {.flags = InputHint, .input = 1};
  1705. XSizeHints *sizeh = NULL;
  1706. sizeh = XAllocSizeHints();
  1707. if(xw.isfixed == False) {
  1708. sizeh->flags = PSize | PResizeInc | PBaseSize;
  1709. sizeh->height = xw.h;
  1710. sizeh->width = xw.w;
  1711. sizeh->height_inc = xw.ch;
  1712. sizeh->width_inc = xw.cw;
  1713. sizeh->base_height = 2*BORDER;
  1714. sizeh->base_width = 2*BORDER;
  1715. } else {
  1716. sizeh->flags = PMaxSize | PMinSize;
  1717. sizeh->min_width = sizeh->max_width = xw.fw;
  1718. sizeh->min_height = sizeh->max_height = xw.fh;
  1719. }
  1720. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  1721. XFree(sizeh);
  1722. }
  1723. XFontSet
  1724. xinitfont(char *fontstr) {
  1725. XFontSet set;
  1726. char *def, **missing;
  1727. int n;
  1728. missing = NULL;
  1729. set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
  1730. if(missing) {
  1731. while(n--)
  1732. fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
  1733. XFreeStringList(missing);
  1734. }
  1735. return set;
  1736. }
  1737. void
  1738. xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
  1739. XFontStruct **xfonts;
  1740. char **font_names;
  1741. int i, n;
  1742. *ascent = *descent = *lbearing = *rbearing = 0;
  1743. n = XFontsOfFontSet(set, &xfonts, &font_names);
  1744. for(i = 0; i < n; i++) {
  1745. *ascent = MAX(*ascent, (*xfonts)->ascent);
  1746. *descent = MAX(*descent, (*xfonts)->descent);
  1747. *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
  1748. *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
  1749. xfonts++;
  1750. }
  1751. }
  1752. void
  1753. initfonts(char *fontstr, char *bfontstr, char *ifontstr) {
  1754. if((dc.font.set = xinitfont(fontstr)) == NULL)
  1755. die("Can't load font %s\n", fontstr);
  1756. if((dc.bfont.set = xinitfont(bfontstr)) == NULL)
  1757. die("Can't load bfont %s\n", bfontstr);
  1758. if((dc.ifont.set = xinitfont(ifontstr)) == NULL)
  1759. die("Can't load ifont %s\n", ifontstr);
  1760. xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
  1761. &dc.font.lbearing, &dc.font.rbearing);
  1762. xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
  1763. &dc.bfont.lbearing, &dc.bfont.rbearing);
  1764. xgetfontinfo(dc.ifont.set, &dc.ifont.ascent, &dc.ifont.descent,
  1765. &dc.ifont.lbearing, &dc.ifont.rbearing);
  1766. }
  1767. void
  1768. xinit(void) {
  1769. XSetWindowAttributes attrs;
  1770. Cursor cursor;
  1771. Window parent;
  1772. int sw, sh;
  1773. if(!(xw.dpy = XOpenDisplay(NULL)))
  1774. die("Can't open display\n");
  1775. xw.scr = XDefaultScreen(xw.dpy);
  1776. /* font */
  1777. initfonts(FONT, BOLDFONT, ITALICFONT);
  1778. /* XXX: Assuming same size for bold font */
  1779. xw.cw = dc.font.rbearing - dc.font.lbearing;
  1780. xw.ch = dc.font.ascent + dc.font.descent;
  1781. /* colors */
  1782. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1783. xloadcols();
  1784. /* adjust fixed window geometry */
  1785. if(xw.isfixed) {
  1786. sw = DisplayWidth(xw.dpy, xw.scr);
  1787. sh = DisplayHeight(xw.dpy, xw.scr);
  1788. if(xw.fx < 0)
  1789. xw.fx = sw + xw.fx - xw.fw - 1;
  1790. if(xw.fy < 0)
  1791. xw.fy = sh + xw.fy - xw.fh - 1;
  1792. xw.h = xw.fh;
  1793. xw.w = xw.fw;
  1794. } else {
  1795. /* window - default size */
  1796. xw.h = 2*BORDER + term.row * xw.ch;
  1797. xw.w = 2*BORDER + term.col * xw.cw;
  1798. xw.fx = 0;
  1799. xw.fy = 0;
  1800. }
  1801. attrs.background_pixel = dc.col[DefaultBG];
  1802. attrs.border_pixel = dc.col[DefaultBG];
  1803. attrs.bit_gravity = NorthWestGravity;
  1804. attrs.event_mask = FocusChangeMask | KeyPressMask
  1805. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1806. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  1807. attrs.colormap = xw.cmap;
  1808. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  1809. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  1810. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  1811. XDefaultVisual(xw.dpy, xw.scr),
  1812. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  1813. | CWColormap,
  1814. &attrs);
  1815. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  1816. /* input methods */
  1817. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  1818. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  1819. | XIMStatusNothing, XNClientWindow, xw.win,
  1820. XNFocusWindow, xw.win, NULL);
  1821. /* gc */
  1822. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  1823. /* white cursor, black outline */
  1824. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  1825. XDefineCursor(xw.dpy, xw.win, cursor);
  1826. XRecolorCursor(xw.dpy, cursor,
  1827. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  1828. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  1829. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1830. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  1831. XMapWindow(xw.dpy, xw.win);
  1832. xhints();
  1833. XSync(xw.dpy, 0);
  1834. }
  1835. void
  1836. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  1837. int fg = base.fg, bg = base.bg, temp;
  1838. int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
  1839. XFontSet fontset = dc.font.set;
  1840. int i;
  1841. /* only switch default fg/bg if term is in RV mode */
  1842. if(IS_SET(MODE_REVERSE)) {
  1843. if(fg == DefaultFG)
  1844. fg = DefaultBG;
  1845. if(bg == DefaultBG)
  1846. bg = DefaultFG;
  1847. }
  1848. if(base.mode & ATTR_REVERSE)
  1849. temp = fg, fg = bg, bg = temp;
  1850. if(base.mode & ATTR_BOLD) {
  1851. fg += 8;
  1852. fontset = dc.bfont.set;
  1853. }
  1854. if(base.mode & ATTR_ITALIC)
  1855. fontset = dc.ifont.set;
  1856. XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
  1857. XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
  1858. if(base.mode & ATTR_GFX) {
  1859. for(i = 0; i < bytelen; i++) {
  1860. char c = gfx[(uint)s[i] % 256];
  1861. if(c)
  1862. s[i] = c;
  1863. else if(s[i] > 0x5f)
  1864. s[i] -= 0x5f;
  1865. }
  1866. }
  1867. XmbDrawImageString(xw.dpy, xw.buf, fontset, dc.gc, winx, winy, s, bytelen);
  1868. if(base.mode & ATTR_UNDERLINE)
  1869. XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
  1870. }
  1871. /* copy buffer pixmap to screen pixmap */
  1872. void
  1873. xcopy() {
  1874. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  1875. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  1876. }
  1877. void
  1878. xdrawcursor(void) {
  1879. static int oldx = 0;
  1880. static int oldy = 0;
  1881. int sl;
  1882. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  1883. LIMIT(oldx, 0, term.col-1);
  1884. LIMIT(oldy, 0, term.row-1);
  1885. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  1886. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  1887. /* remove the old cursor */
  1888. if(term.line[oldy][oldx].state & GLYPH_SET) {
  1889. sl = utf8size(term.line[oldy][oldx].c);
  1890. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
  1891. } else
  1892. xclear(oldx, oldy, oldx, oldy);
  1893. xcopy();
  1894. /* draw the new one */
  1895. if(!(term.c.state & CURSOR_HIDE)) {
  1896. if(!(xw.state & WIN_FOCUSED))
  1897. g.bg = DefaultUCS;
  1898. if(IS_SET(MODE_REVERSE))
  1899. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  1900. sl = utf8size(g.c);
  1901. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  1902. oldx = term.c.x, oldy = term.c.y;
  1903. }
  1904. xcopy();
  1905. }
  1906. void
  1907. redraw(void) {
  1908. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  1909. tfulldirt();
  1910. draw();
  1911. nanosleep(&tv, NULL);
  1912. }
  1913. void
  1914. draw() {
  1915. drawregion(0, 0, term.col, term.row);
  1916. xcopy();
  1917. gettimeofday(&xw.lastdraw, NULL);
  1918. }
  1919. void
  1920. drawregion(int x1, int y1, int x2, int y2) {
  1921. int ic, ib, x, y, ox, sl;
  1922. Glyph base, new;
  1923. char buf[DRAW_BUF_SIZ];
  1924. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
  1925. if((sel.alt && !alt) || (!sel.alt && alt))
  1926. ena_sel = 0;
  1927. if(!(xw.state & WIN_VISIBLE))
  1928. return;
  1929. for(y = y1; y < y2; y++) {
  1930. if(!term.dirty[y])
  1931. continue;
  1932. xclear(0, y, term.col, y);
  1933. term.dirty[y] = 0;
  1934. base = term.line[y][0];
  1935. ic = ib = ox = 0;
  1936. for(x = x1; x < x2; x++) {
  1937. new = term.line[y][x];
  1938. if(ena_sel && *(new.c) && selected(x, y))
  1939. new.mode ^= ATTR_REVERSE;
  1940. if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
  1941. ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  1942. xdraws(buf, base, ox, y, ic, ib);
  1943. ic = ib = 0;
  1944. }
  1945. if(new.state & GLYPH_SET) {
  1946. if(ib == 0) {
  1947. ox = x;
  1948. base = new;
  1949. }
  1950. sl = utf8size(new.c);
  1951. memcpy(buf+ib, new.c, sl);
  1952. ib += sl;
  1953. ++ic;
  1954. }
  1955. }
  1956. if(ib > 0)
  1957. xdraws(buf, base, ox, y, ic, ib);
  1958. }
  1959. xdrawcursor();
  1960. }
  1961. void
  1962. expose(XEvent *ev) {
  1963. XExposeEvent *e = &ev->xexpose;
  1964. if(xw.state & WIN_REDRAW) {
  1965. if(!e->count)
  1966. xw.state &= ~WIN_REDRAW;
  1967. }
  1968. xcopy();
  1969. }
  1970. void
  1971. visibility(XEvent *ev) {
  1972. XVisibilityEvent *e = &ev->xvisibility;
  1973. if(e->state == VisibilityFullyObscured)
  1974. xw.state &= ~WIN_VISIBLE;
  1975. else if(!(xw.state & WIN_VISIBLE))
  1976. /* need a full redraw for next Expose, not just a buf copy */
  1977. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  1978. }
  1979. void
  1980. unmap(XEvent *ev) {
  1981. xw.state &= ~WIN_VISIBLE;
  1982. }
  1983. void
  1984. xseturgency(int add) {
  1985. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1986. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  1987. XSetWMHints(xw.dpy, xw.win, h);
  1988. XFree(h);
  1989. }
  1990. void
  1991. focus(XEvent *ev) {
  1992. if(ev->type == FocusIn) {
  1993. xw.state |= WIN_FOCUSED;
  1994. xseturgency(0);
  1995. } else
  1996. xw.state &= ~WIN_FOCUSED;
  1997. draw();
  1998. }
  1999. char*
  2000. kmap(KeySym k, uint state) {
  2001. int i;
  2002. state &= ~Mod2Mask;
  2003. for(i = 0; i < LEN(key); i++) {
  2004. uint mask = key[i].mask;
  2005. if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
  2006. return (char*)key[i].s;
  2007. }
  2008. return NULL;
  2009. }
  2010. void
  2011. kpress(XEvent *ev) {
  2012. XKeyEvent *e = &ev->xkey;
  2013. KeySym ksym;
  2014. char buf[32];
  2015. char *customkey;
  2016. int len;
  2017. int meta;
  2018. int shift;
  2019. Status status;
  2020. meta = e->state & Mod1Mask;
  2021. shift = e->state & ShiftMask;
  2022. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  2023. /* 1. custom keys from config.h */
  2024. if((customkey = kmap(ksym, e->state)))
  2025. ttywrite(customkey, strlen(customkey));
  2026. /* 2. hardcoded (overrides X lookup) */
  2027. else
  2028. switch(ksym) {
  2029. case XK_Up:
  2030. case XK_Down:
  2031. case XK_Left:
  2032. case XK_Right:
  2033. /* XXX: shift up/down doesn't work */
  2034. sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
  2035. ttywrite(buf, 3);
  2036. break;
  2037. case XK_Insert:
  2038. if(shift)
  2039. selpaste();
  2040. break;
  2041. case XK_Return:
  2042. if(IS_SET(MODE_CRLF))
  2043. ttywrite("\r\n", 2);
  2044. else
  2045. ttywrite("\r", 1);
  2046. break;
  2047. /* 3. X lookup */
  2048. default:
  2049. if(len > 0) {
  2050. if(meta && len == 1)
  2051. ttywrite("\033", 1);
  2052. ttywrite(buf, len);
  2053. }
  2054. break;
  2055. }
  2056. }
  2057. void
  2058. cmessage(XEvent *e) {
  2059. /* See xembed specs
  2060. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2061. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2062. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2063. xw.state |= WIN_FOCUSED;
  2064. xseturgency(0);
  2065. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2066. xw.state &= ~WIN_FOCUSED;
  2067. }
  2068. draw();
  2069. }
  2070. }
  2071. void
  2072. resize(XEvent *e) {
  2073. int col, row;
  2074. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2075. return;
  2076. xw.w = e->xconfigure.width;
  2077. xw.h = e->xconfigure.height;
  2078. col = (xw.w - 2*BORDER) / xw.cw;
  2079. row = (xw.h - 2*BORDER) / xw.ch;
  2080. if(col == term.col && row == term.row)
  2081. return;
  2082. if(tresize(col, row))
  2083. draw();
  2084. xresize(col, row);
  2085. ttyresize(col, row);
  2086. }
  2087. bool
  2088. last_draw_too_old(void) {
  2089. struct timeval now;
  2090. gettimeofday(&now, NULL);
  2091. return TIMEDIFF(now, xw.lastdraw) >= DRAW_TIMEOUT/1000;
  2092. }
  2093. void
  2094. run(void) {
  2095. XEvent ev;
  2096. fd_set rfd;
  2097. int xfd = XConnectionNumber(xw.dpy);
  2098. struct timeval timeout = {0};
  2099. bool stuff_to_print = 0;
  2100. for(;;) {
  2101. FD_ZERO(&rfd);
  2102. FD_SET(cmdfd, &rfd);
  2103. FD_SET(xfd, &rfd);
  2104. timeout.tv_sec = 0;
  2105. timeout.tv_usec = SELECT_TIMEOUT;
  2106. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, &timeout) < 0) {
  2107. if(errno == EINTR)
  2108. continue;
  2109. die("select failed: %s\n", SERRNO);
  2110. }
  2111. if(FD_ISSET(cmdfd, &rfd)) {
  2112. ttyread();
  2113. stuff_to_print = 1;
  2114. }
  2115. if(stuff_to_print && last_draw_too_old()) {
  2116. stuff_to_print = 0;
  2117. draw();
  2118. }
  2119. while(XPending(xw.dpy)) {
  2120. XNextEvent(xw.dpy, &ev);
  2121. if(XFilterEvent(&ev, xw.win))
  2122. continue;
  2123. if(handler[ev.type])
  2124. (handler[ev.type])(&ev);
  2125. }
  2126. }
  2127. }
  2128. int
  2129. main(int argc, char *argv[]) {
  2130. int i, bitm, xr, yr;
  2131. unsigned int wr, hr;
  2132. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2133. xw.isfixed = False;
  2134. for(i = 1; i < argc; i++) {
  2135. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2136. case 't':
  2137. if(++i < argc) opt_title = argv[i];
  2138. break;
  2139. case 'c':
  2140. if(++i < argc) opt_class = argv[i];
  2141. break;
  2142. case 'w':
  2143. if(++i < argc) opt_embed = argv[i];
  2144. break;
  2145. case 'f':
  2146. if(++i < argc) opt_io = argv[i];
  2147. break;
  2148. case 'e':
  2149. /* eat every remaining arguments */
  2150. if(++i < argc) opt_cmd = &argv[i];
  2151. goto run;
  2152. case 'g':
  2153. if(++i >= argc)
  2154. break;
  2155. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2156. if(bitm & XValue)
  2157. xw.fx = xr;
  2158. if(bitm & YValue)
  2159. xw.fy = yr;
  2160. if(bitm & WidthValue)
  2161. xw.fw = (int)wr;
  2162. if(bitm & HeightValue)
  2163. xw.fh = (int)hr;
  2164. if(bitm & XNegative && xw.fx == 0)
  2165. xw.fx = -1;
  2166. if(bitm & XNegative && xw.fy == 0)
  2167. xw.fy = -1;
  2168. if(xw.fh != 0 && xw.fw != 0)
  2169. xw.isfixed = True;
  2170. break;
  2171. case 'v':
  2172. default:
  2173. die(USAGE);
  2174. }
  2175. }
  2176. run:
  2177. setlocale(LC_CTYPE, "");
  2178. tnew(80, 24);
  2179. ttynew();
  2180. xinit();
  2181. selinit();
  2182. run();
  2183. return 0;
  2184. }