st.c 64 KB

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