st.c 85 KB

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