st.c 54 KB

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