st.c 85 KB

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