st.c 73 KB

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