st.c 86 KB

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