st.c 73 KB

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