st.c 78 KB

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