st.c 75 KB

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