st.c 63 KB

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