st.c 74 KB

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