st.c 71 KB

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