st.c 63 KB

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