st.c 77 KB

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