st.c 54 KB

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