st.c 77 KB

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