st.c 61 KB

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