st.c 80 KB

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