st.c 79 KB

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