st.c 86 KB

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