st.c 63 KB

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