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