st.c 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936
  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_REVERSE = 32,
  86. ATTR_INVISIBLE = 64,
  87. ATTR_STRUCK = 128,
  88. ATTR_WRAP = 256,
  89. ATTR_WIDE = 512,
  90. ATTR_WDUMMY = 1024,
  91. };
  92. enum cursor_movement {
  93. CURSOR_SAVE,
  94. CURSOR_LOAD
  95. };
  96. enum cursor_state {
  97. CURSOR_DEFAULT = 0,
  98. CURSOR_WRAPNEXT = 1,
  99. CURSOR_ORIGIN = 2
  100. };
  101. enum term_mode {
  102. MODE_WRAP = 1,
  103. MODE_INSERT = 2,
  104. MODE_APPKEYPAD = 4,
  105. MODE_ALTSCREEN = 8,
  106. MODE_CRLF = 16,
  107. MODE_MOUSEBTN = 32,
  108. MODE_MOUSEMOTION = 64,
  109. MODE_REVERSE = 128,
  110. MODE_KBDLOCK = 256,
  111. MODE_HIDE = 512,
  112. MODE_ECHO = 1024,
  113. MODE_APPCURSOR = 2048,
  114. MODE_MOUSESGR = 4096,
  115. MODE_8BIT = 8192,
  116. MODE_BLINK = 16384,
  117. MODE_FBLINK = 32768,
  118. MODE_FOCUS = 65536,
  119. MODE_MOUSEX10 = 131072,
  120. MODE_MOUSEMANY = 262144,
  121. MODE_BRCKTPASTE = 524288,
  122. MODE_PRINT = 1048576,
  123. MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
  124. |MODE_MOUSEMANY,
  125. };
  126. enum charset {
  127. CS_GRAPHIC0,
  128. CS_GRAPHIC1,
  129. CS_UK,
  130. CS_USA,
  131. CS_MULTI,
  132. CS_GER,
  133. CS_FIN
  134. };
  135. enum escape_state {
  136. ESC_START = 1,
  137. ESC_CSI = 2,
  138. ESC_STR = 4, /* DCS, OSC, PM, APC */
  139. ESC_ALTCHARSET = 8,
  140. ESC_STR_END = 16, /* a final string was encountered */
  141. ESC_TEST = 32, /* Enter in test mode */
  142. };
  143. enum window_state {
  144. WIN_VISIBLE = 1,
  145. WIN_REDRAW = 2,
  146. WIN_FOCUSED = 4
  147. };
  148. enum selection_type {
  149. SEL_REGULAR = 1,
  150. SEL_RECTANGULAR = 2
  151. };
  152. enum selection_snap {
  153. SNAP_WORD = 1,
  154. SNAP_LINE = 2
  155. };
  156. typedef unsigned char uchar;
  157. typedef unsigned int uint;
  158. typedef unsigned long ulong;
  159. typedef unsigned short ushort;
  160. typedef XftDraw *Draw;
  161. typedef XftColor Color;
  162. typedef struct {
  163. char c[UTF_SIZ]; /* character code */
  164. ushort mode; /* attribute flags */
  165. uint32_t fg; /* foreground */
  166. uint32_t bg; /* background */
  167. } Glyph;
  168. typedef Glyph *Line;
  169. typedef struct {
  170. Glyph attr; /* current char attributes */
  171. int x;
  172. int y;
  173. char state;
  174. } TCursor;
  175. /* CSI Escape sequence structs */
  176. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  177. typedef struct {
  178. char buf[ESC_BUF_SIZ]; /* raw string */
  179. int len; /* raw string length */
  180. char priv;
  181. int arg[ESC_ARG_SIZ];
  182. int narg; /* nb of args */
  183. char mode;
  184. } CSIEscape;
  185. /* STR Escape sequence structs */
  186. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  187. typedef struct {
  188. char type; /* ESC type ... */
  189. char buf[STR_BUF_SIZ]; /* raw string */
  190. int len; /* raw string length */
  191. char *args[STR_ARG_SIZ];
  192. int narg; /* nb of args */
  193. } STREscape;
  194. /* Internal representation of the screen */
  195. typedef struct {
  196. int row; /* nb row */
  197. int col; /* nb col */
  198. Line *line; /* screen */
  199. Line *alt; /* alternate screen */
  200. bool *dirty; /* dirtyness of lines */
  201. TCursor c; /* cursor */
  202. int top; /* top scroll limit */
  203. int bot; /* bottom scroll limit */
  204. int mode; /* terminal mode flags */
  205. int esc; /* escape state flags */
  206. char trantbl[4]; /* charset table translation */
  207. int charset; /* current charset */
  208. int icharset; /* selected charset for sequence */
  209. bool numlock; /* lock numbers in keyboard */
  210. bool *tabs;
  211. } Term;
  212. /* Purely graphic info */
  213. typedef struct {
  214. Display *dpy;
  215. Colormap cmap;
  216. Window win;
  217. Drawable buf;
  218. Atom xembed, wmdeletewin, netwmname, netwmpid;
  219. XIM xim;
  220. XIC xic;
  221. Draw draw;
  222. Visual *vis;
  223. XSetWindowAttributes attrs;
  224. int scr;
  225. bool isfixed; /* is fixed geometry? */
  226. int l, t; /* left and top offset */
  227. int gm; /* geometry mask */
  228. int tw, th; /* tty width and height */
  229. int w, h; /* window width and height */
  230. int ch; /* char height */
  231. int cw; /* char width */
  232. char state; /* focus, redraw, visible */
  233. } XWindow;
  234. typedef struct {
  235. uint b;
  236. uint mask;
  237. char *s;
  238. } Mousekey;
  239. typedef struct {
  240. KeySym k;
  241. uint mask;
  242. char *s;
  243. /* three valued logic variables: 0 indifferent, 1 on, -1 off */
  244. signed char appkey; /* application keypad */
  245. signed char appcursor; /* application cursor */
  246. signed char crlf; /* crlf mode */
  247. } Key;
  248. typedef struct {
  249. int mode;
  250. int type;
  251. int snap;
  252. /*
  253. * Selection variables:
  254. * nb – normalized coordinates of the beginning of the selection
  255. * ne – normalized coordinates of the end of the selection
  256. * ob – original coordinates of the beginning of the selection
  257. * oe – original coordinates of the end of the selection
  258. */
  259. struct {
  260. int x, y;
  261. } nb, ne, ob, oe;
  262. char *clip;
  263. Atom xtarget;
  264. bool alt;
  265. struct timespec tclick1;
  266. struct timespec tclick2;
  267. } Selection;
  268. typedef union {
  269. int i;
  270. uint ui;
  271. float f;
  272. const void *v;
  273. } Arg;
  274. typedef struct {
  275. uint mod;
  276. KeySym keysym;
  277. void (*func)(const Arg *);
  278. const Arg arg;
  279. } Shortcut;
  280. /* function definitions used in config.h */
  281. static void clippaste(const Arg *);
  282. static void numlock(const Arg *);
  283. static void selpaste(const Arg *);
  284. static void xzoom(const Arg *);
  285. static void printsel(const Arg *);
  286. static void printscreen(const Arg *) ;
  287. static void toggleprinter(const Arg *);
  288. /* Config.h for applying patches and the configuration. */
  289. #include "config.h"
  290. /* Font structure */
  291. typedef struct {
  292. int height;
  293. int width;
  294. int ascent;
  295. int descent;
  296. short lbearing;
  297. short rbearing;
  298. XftFont *match;
  299. FcFontSet *set;
  300. FcPattern *pattern;
  301. } Font;
  302. /* Drawing Context */
  303. typedef struct {
  304. Color col[MAX(LEN(colorname), 256)];
  305. Font font, bfont, ifont, ibfont;
  306. GC gc;
  307. } DC;
  308. static void die(const char *, ...);
  309. static void draw(void);
  310. static void redraw(int);
  311. static void drawregion(int, int, int, int);
  312. static void execsh(void);
  313. static void sigchld(int);
  314. static void run(void);
  315. static void csidump(void);
  316. static void csihandle(void);
  317. static void csiparse(void);
  318. static void csireset(void);
  319. static void strdump(void);
  320. static void strhandle(void);
  321. static void strparse(void);
  322. static void strreset(void);
  323. static int tattrset(int);
  324. static void tprinter(char *, size_t);
  325. static void tdumpsel(void);
  326. static void tdumpline(int);
  327. static void tdump(void);
  328. static void tclearregion(int, int, int, int);
  329. static void tcursor(int);
  330. static void tdeletechar(int);
  331. static void tdeleteline(int);
  332. static void tinsertblank(int);
  333. static void tinsertblankline(int);
  334. static int tlinelen(int);
  335. static void tmoveto(int, int);
  336. static void tmoveato(int, int);
  337. static void tnew(int, int);
  338. static void tnewline(int);
  339. static void tputtab(int);
  340. static void tputc(char *, int);
  341. static void treset(void);
  342. static int tresize(int, int);
  343. static void tscrollup(int, int);
  344. static void tscrolldown(int, int);
  345. static void tsetattr(int *, int);
  346. static void tsetchar(char *, Glyph *, int, int);
  347. static void tsetscroll(int, int);
  348. static void tswapscreen(void);
  349. static void tsetdirt(int, int);
  350. static void tsetdirtattr(int);
  351. static void tsetmode(bool, bool, int *, int);
  352. static void tfulldirt(void);
  353. static void techo(char *, int);
  354. static void tcontrolcode(uchar );
  355. static void tdectest(char );
  356. static int32_t tdefcolor(int *, int *, int);
  357. static void tdeftran(char);
  358. static inline bool match(uint, uint);
  359. static void ttynew(void);
  360. static void ttyread(void);
  361. static void ttyresize(void);
  362. static void ttysend(char *, size_t);
  363. static void ttywrite(const char *, size_t);
  364. static void tstrsequence(uchar c);
  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_REVERSE |
  1461. ATTR_INVISIBLE |
  1462. ATTR_STRUCK );
  1463. term.c.attr.fg = defaultfg;
  1464. term.c.attr.bg = defaultbg;
  1465. break;
  1466. case 1:
  1467. term.c.attr.mode |= ATTR_BOLD;
  1468. break;
  1469. case 2:
  1470. term.c.attr.mode |= ATTR_FAINT;
  1471. break;
  1472. case 3:
  1473. term.c.attr.mode |= ATTR_ITALIC;
  1474. break;
  1475. case 4:
  1476. term.c.attr.mode |= ATTR_UNDERLINE;
  1477. break;
  1478. case 5: /* slow blink */
  1479. /* FALLTHROUGH */
  1480. case 6: /* rapid blink */
  1481. term.c.attr.mode |= ATTR_BLINK;
  1482. break;
  1483. case 7:
  1484. term.c.attr.mode |= ATTR_REVERSE;
  1485. break;
  1486. case 8:
  1487. term.c.attr.mode |= ATTR_INVISIBLE;
  1488. break;
  1489. case 9:
  1490. term.c.attr.mode |= ATTR_STRUCK;
  1491. break;
  1492. case 22:
  1493. term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
  1494. break;
  1495. case 23:
  1496. term.c.attr.mode &= ~ATTR_ITALIC;
  1497. break;
  1498. case 24:
  1499. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1500. break;
  1501. case 25:
  1502. term.c.attr.mode &= ~ATTR_BLINK;
  1503. break;
  1504. case 27:
  1505. term.c.attr.mode &= ~ATTR_REVERSE;
  1506. break;
  1507. case 28:
  1508. term.c.attr.mode &= ~ATTR_INVISIBLE;
  1509. break;
  1510. case 29:
  1511. term.c.attr.mode &= ~ATTR_STRUCK;
  1512. break;
  1513. case 38:
  1514. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1515. term.c.attr.fg = idx;
  1516. break;
  1517. case 39:
  1518. term.c.attr.fg = defaultfg;
  1519. break;
  1520. case 48:
  1521. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1522. term.c.attr.bg = idx;
  1523. break;
  1524. case 49:
  1525. term.c.attr.bg = defaultbg;
  1526. break;
  1527. default:
  1528. if(BETWEEN(attr[i], 30, 37)) {
  1529. term.c.attr.fg = attr[i] - 30;
  1530. } else if(BETWEEN(attr[i], 40, 47)) {
  1531. term.c.attr.bg = attr[i] - 40;
  1532. } else if(BETWEEN(attr[i], 90, 97)) {
  1533. term.c.attr.fg = attr[i] - 90 + 8;
  1534. } else if(BETWEEN(attr[i], 100, 107)) {
  1535. term.c.attr.bg = attr[i] - 100 + 8;
  1536. } else {
  1537. fprintf(stderr,
  1538. "erresc(default): gfx attr %d unknown\n",
  1539. attr[i]), csidump();
  1540. }
  1541. break;
  1542. }
  1543. }
  1544. }
  1545. void
  1546. tsetscroll(int t, int b) {
  1547. int temp;
  1548. LIMIT(t, 0, term.row-1);
  1549. LIMIT(b, 0, term.row-1);
  1550. if(t > b) {
  1551. temp = t;
  1552. t = b;
  1553. b = temp;
  1554. }
  1555. term.top = t;
  1556. term.bot = b;
  1557. }
  1558. void
  1559. tsetmode(bool priv, bool set, int *args, int narg) {
  1560. int *lim, mode;
  1561. bool alt;
  1562. for(lim = args + narg; args < lim; ++args) {
  1563. if(priv) {
  1564. switch(*args) {
  1565. case 1: /* DECCKM -- Cursor key */
  1566. MODBIT(term.mode, set, MODE_APPCURSOR);
  1567. break;
  1568. case 5: /* DECSCNM -- Reverse video */
  1569. mode = term.mode;
  1570. MODBIT(term.mode, set, MODE_REVERSE);
  1571. if(mode != term.mode)
  1572. redraw(REDRAW_TIMEOUT);
  1573. break;
  1574. case 6: /* DECOM -- Origin */
  1575. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1576. tmoveato(0, 0);
  1577. break;
  1578. case 7: /* DECAWM -- Auto wrap */
  1579. MODBIT(term.mode, set, MODE_WRAP);
  1580. break;
  1581. case 0: /* Error (IGNORED) */
  1582. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1583. case 3: /* DECCOLM -- Column (IGNORED) */
  1584. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1585. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1586. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1587. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1588. case 42: /* DECNRCM -- National characters (IGNORED) */
  1589. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1590. break;
  1591. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1592. MODBIT(term.mode, !set, MODE_HIDE);
  1593. break;
  1594. case 9: /* X10 mouse compatibility mode */
  1595. xsetpointermotion(0);
  1596. MODBIT(term.mode, 0, MODE_MOUSE);
  1597. MODBIT(term.mode, set, MODE_MOUSEX10);
  1598. break;
  1599. case 1000: /* 1000: report button press */
  1600. xsetpointermotion(0);
  1601. MODBIT(term.mode, 0, MODE_MOUSE);
  1602. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1603. break;
  1604. case 1002: /* 1002: report motion on button press */
  1605. xsetpointermotion(0);
  1606. MODBIT(term.mode, 0, MODE_MOUSE);
  1607. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1608. break;
  1609. case 1003: /* 1003: enable all mouse motions */
  1610. xsetpointermotion(set);
  1611. MODBIT(term.mode, 0, MODE_MOUSE);
  1612. MODBIT(term.mode, set, MODE_MOUSEMANY);
  1613. break;
  1614. case 1004: /* 1004: send focus events to tty */
  1615. MODBIT(term.mode, set, MODE_FOCUS);
  1616. break;
  1617. case 1006: /* 1006: extended reporting mode */
  1618. MODBIT(term.mode, set, MODE_MOUSESGR);
  1619. break;
  1620. case 1034:
  1621. MODBIT(term.mode, set, MODE_8BIT);
  1622. break;
  1623. case 1049: /* swap screen & set/restore cursor as xterm */
  1624. if (!allowaltscreen)
  1625. break;
  1626. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1627. /* FALLTHROUGH */
  1628. case 47: /* swap screen */
  1629. case 1047:
  1630. if (!allowaltscreen)
  1631. break;
  1632. alt = IS_SET(MODE_ALTSCREEN);
  1633. if(alt) {
  1634. tclearregion(0, 0, term.col-1,
  1635. term.row-1);
  1636. }
  1637. if(set ^ alt) /* set is always 1 or 0 */
  1638. tswapscreen();
  1639. if(*args != 1049)
  1640. break;
  1641. /* FALLTHROUGH */
  1642. case 1048:
  1643. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1644. break;
  1645. case 2004: /* 2004: bracketed paste mode */
  1646. MODBIT(term.mode, set, MODE_BRCKTPASTE);
  1647. break;
  1648. /* Not implemented mouse modes. See comments there. */
  1649. case 1001: /* mouse highlight mode; can hang the
  1650. terminal by design when implemented. */
  1651. case 1005: /* UTF-8 mouse mode; will confuse
  1652. applications not supporting UTF-8
  1653. and luit. */
  1654. case 1015: /* urxvt mangled mouse mode; incompatible
  1655. and can be mistaken for other control
  1656. codes. */
  1657. default:
  1658. fprintf(stderr,
  1659. "erresc: unknown private set/reset mode %d\n",
  1660. *args);
  1661. break;
  1662. }
  1663. } else {
  1664. switch(*args) {
  1665. case 0: /* Error (IGNORED) */
  1666. break;
  1667. case 2: /* KAM -- keyboard action */
  1668. MODBIT(term.mode, set, MODE_KBDLOCK);
  1669. break;
  1670. case 4: /* IRM -- Insertion-replacement */
  1671. MODBIT(term.mode, set, MODE_INSERT);
  1672. break;
  1673. case 12: /* SRM -- Send/Receive */
  1674. MODBIT(term.mode, !set, MODE_ECHO);
  1675. break;
  1676. case 20: /* LNM -- Linefeed/new line */
  1677. MODBIT(term.mode, set, MODE_CRLF);
  1678. break;
  1679. default:
  1680. fprintf(stderr,
  1681. "erresc: unknown set/reset mode %d\n",
  1682. *args);
  1683. break;
  1684. }
  1685. }
  1686. }
  1687. }
  1688. void
  1689. csihandle(void) {
  1690. char buf[40];
  1691. int len;
  1692. switch(csiescseq.mode) {
  1693. default:
  1694. unknown:
  1695. fprintf(stderr, "erresc: unknown csi ");
  1696. csidump();
  1697. /* die(""); */
  1698. break;
  1699. case '@': /* ICH -- Insert <n> blank char */
  1700. DEFAULT(csiescseq.arg[0], 1);
  1701. tinsertblank(csiescseq.arg[0]);
  1702. break;
  1703. case 'A': /* CUU -- Cursor <n> Up */
  1704. DEFAULT(csiescseq.arg[0], 1);
  1705. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1706. break;
  1707. case 'B': /* CUD -- Cursor <n> Down */
  1708. case 'e': /* VPR --Cursor <n> Down */
  1709. DEFAULT(csiescseq.arg[0], 1);
  1710. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1711. break;
  1712. case 'i': /* MC -- Media Copy */
  1713. switch(csiescseq.arg[0]) {
  1714. case 0:
  1715. tdump();
  1716. break;
  1717. case 1:
  1718. tdumpline(term.c.y);
  1719. break;
  1720. case 2:
  1721. tdumpsel();
  1722. break;
  1723. case 4:
  1724. term.mode &= ~MODE_PRINT;
  1725. break;
  1726. case 5:
  1727. term.mode |= MODE_PRINT;
  1728. break;
  1729. }
  1730. break;
  1731. case 'c': /* DA -- Device Attributes */
  1732. if(csiescseq.arg[0] == 0)
  1733. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1734. break;
  1735. case 'C': /* CUF -- Cursor <n> Forward */
  1736. case 'a': /* HPR -- Cursor <n> Forward */
  1737. DEFAULT(csiescseq.arg[0], 1);
  1738. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1739. break;
  1740. case 'D': /* CUB -- Cursor <n> Backward */
  1741. DEFAULT(csiescseq.arg[0], 1);
  1742. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1743. break;
  1744. case 'E': /* CNL -- Cursor <n> Down and first col */
  1745. DEFAULT(csiescseq.arg[0], 1);
  1746. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1747. break;
  1748. case 'F': /* CPL -- Cursor <n> Up and first col */
  1749. DEFAULT(csiescseq.arg[0], 1);
  1750. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1751. break;
  1752. case 'g': /* TBC -- Tabulation clear */
  1753. switch(csiescseq.arg[0]) {
  1754. case 0: /* clear current tab stop */
  1755. term.tabs[term.c.x] = 0;
  1756. break;
  1757. case 3: /* clear all the tabs */
  1758. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1759. break;
  1760. default:
  1761. goto unknown;
  1762. }
  1763. break;
  1764. case 'G': /* CHA -- Move to <col> */
  1765. case '`': /* HPA */
  1766. DEFAULT(csiescseq.arg[0], 1);
  1767. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1768. break;
  1769. case 'H': /* CUP -- Move to <row> <col> */
  1770. case 'f': /* HVP */
  1771. DEFAULT(csiescseq.arg[0], 1);
  1772. DEFAULT(csiescseq.arg[1], 1);
  1773. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1774. break;
  1775. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1776. DEFAULT(csiescseq.arg[0], 1);
  1777. tputtab(csiescseq.arg[0]);
  1778. break;
  1779. case 'J': /* ED -- Clear screen */
  1780. selclear(NULL);
  1781. switch(csiescseq.arg[0]) {
  1782. case 0: /* below */
  1783. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1784. if(term.c.y < term.row-1) {
  1785. tclearregion(0, term.c.y+1, term.col-1,
  1786. term.row-1);
  1787. }
  1788. break;
  1789. case 1: /* above */
  1790. if(term.c.y > 1)
  1791. tclearregion(0, 0, term.col-1, term.c.y-1);
  1792. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1793. break;
  1794. case 2: /* all */
  1795. tclearregion(0, 0, term.col-1, term.row-1);
  1796. break;
  1797. default:
  1798. goto unknown;
  1799. }
  1800. break;
  1801. case 'K': /* EL -- Clear line */
  1802. switch(csiescseq.arg[0]) {
  1803. case 0: /* right */
  1804. tclearregion(term.c.x, term.c.y, term.col-1,
  1805. term.c.y);
  1806. break;
  1807. case 1: /* left */
  1808. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1809. break;
  1810. case 2: /* all */
  1811. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1812. break;
  1813. }
  1814. break;
  1815. case 'S': /* SU -- Scroll <n> line up */
  1816. DEFAULT(csiescseq.arg[0], 1);
  1817. tscrollup(term.top, csiescseq.arg[0]);
  1818. break;
  1819. case 'T': /* SD -- Scroll <n> line down */
  1820. DEFAULT(csiescseq.arg[0], 1);
  1821. tscrolldown(term.top, csiescseq.arg[0]);
  1822. break;
  1823. case 'L': /* IL -- Insert <n> blank lines */
  1824. DEFAULT(csiescseq.arg[0], 1);
  1825. tinsertblankline(csiescseq.arg[0]);
  1826. break;
  1827. case 'l': /* RM -- Reset Mode */
  1828. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1829. break;
  1830. case 'M': /* DL -- Delete <n> lines */
  1831. DEFAULT(csiescseq.arg[0], 1);
  1832. tdeleteline(csiescseq.arg[0]);
  1833. break;
  1834. case 'X': /* ECH -- Erase <n> char */
  1835. DEFAULT(csiescseq.arg[0], 1);
  1836. tclearregion(term.c.x, term.c.y,
  1837. term.c.x + csiescseq.arg[0] - 1, term.c.y);
  1838. break;
  1839. case 'P': /* DCH -- Delete <n> char */
  1840. DEFAULT(csiescseq.arg[0], 1);
  1841. tdeletechar(csiescseq.arg[0]);
  1842. break;
  1843. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1844. DEFAULT(csiescseq.arg[0], 1);
  1845. tputtab(-csiescseq.arg[0]);
  1846. break;
  1847. case 'd': /* VPA -- Move to <row> */
  1848. DEFAULT(csiescseq.arg[0], 1);
  1849. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1850. break;
  1851. case 'h': /* SM -- Set terminal mode */
  1852. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1853. break;
  1854. case 'm': /* SGR -- Terminal attribute (color) */
  1855. tsetattr(csiescseq.arg, csiescseq.narg);
  1856. break;
  1857. case 'n': /* DSR – Device Status Report (cursor position) */
  1858. if (csiescseq.arg[0] == 6) {
  1859. len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
  1860. term.c.y+1, term.c.x+1);
  1861. ttywrite(buf, len);
  1862. }
  1863. break;
  1864. case 'r': /* DECSTBM -- Set Scrolling Region */
  1865. if(csiescseq.priv) {
  1866. goto unknown;
  1867. } else {
  1868. DEFAULT(csiescseq.arg[0], 1);
  1869. DEFAULT(csiescseq.arg[1], term.row);
  1870. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1871. tmoveato(0, 0);
  1872. }
  1873. break;
  1874. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1875. tcursor(CURSOR_SAVE);
  1876. break;
  1877. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1878. tcursor(CURSOR_LOAD);
  1879. break;
  1880. }
  1881. }
  1882. void
  1883. csidump(void) {
  1884. int i;
  1885. uint c;
  1886. printf("ESC[");
  1887. for(i = 0; i < csiescseq.len; i++) {
  1888. c = csiescseq.buf[i] & 0xff;
  1889. if(isprint(c)) {
  1890. putchar(c);
  1891. } else if(c == '\n') {
  1892. printf("(\\n)");
  1893. } else if(c == '\r') {
  1894. printf("(\\r)");
  1895. } else if(c == 0x1b) {
  1896. printf("(\\e)");
  1897. } else {
  1898. printf("(%02x)", c);
  1899. }
  1900. }
  1901. putchar('\n');
  1902. }
  1903. void
  1904. csireset(void) {
  1905. memset(&csiescseq, 0, sizeof(csiescseq));
  1906. }
  1907. void
  1908. strhandle(void) {
  1909. char *p = NULL;
  1910. int j, narg, par;
  1911. term.esc &= ~(ESC_STR_END|ESC_STR);
  1912. strparse();
  1913. narg = strescseq.narg;
  1914. par = atoi(strescseq.args[0]);
  1915. switch(strescseq.type) {
  1916. case ']': /* OSC -- Operating System Command */
  1917. switch(par) {
  1918. case 0:
  1919. case 1:
  1920. case 2:
  1921. if(narg > 1)
  1922. xsettitle(strescseq.args[1]);
  1923. return;
  1924. case 4: /* color set */
  1925. if(narg < 3)
  1926. break;
  1927. p = strescseq.args[2];
  1928. /* FALLTHROUGH */
  1929. case 104: /* color reset, here p = NULL */
  1930. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  1931. if(xsetcolorname(j, p)) {
  1932. fprintf(stderr, "erresc: invalid color %s\n", p);
  1933. } else {
  1934. /*
  1935. * TODO if defaultbg color is changed, borders
  1936. * are dirty
  1937. */
  1938. redraw(0);
  1939. }
  1940. return;
  1941. }
  1942. break;
  1943. case 'k': /* old title set compatibility */
  1944. xsettitle(strescseq.args[0]);
  1945. return;
  1946. case 'P': /* DCS -- Device Control String */
  1947. case '_': /* APC -- Application Program Command */
  1948. case '^': /* PM -- Privacy Message */
  1949. return;
  1950. }
  1951. fprintf(stderr, "erresc: unknown str ");
  1952. strdump();
  1953. }
  1954. void
  1955. strparse(void) {
  1956. char *p = strescseq.buf;
  1957. strescseq.narg = 0;
  1958. strescseq.buf[strescseq.len] = '\0';
  1959. while(p && strescseq.narg < STR_ARG_SIZ)
  1960. strescseq.args[strescseq.narg++] = strsep(&p, ";");
  1961. }
  1962. void
  1963. strdump(void) {
  1964. int i;
  1965. uint c;
  1966. printf("ESC%c", strescseq.type);
  1967. for(i = 0; i < strescseq.len; i++) {
  1968. c = strescseq.buf[i] & 0xff;
  1969. if(c == '\0') {
  1970. return;
  1971. } else if(isprint(c)) {
  1972. putchar(c);
  1973. } else if(c == '\n') {
  1974. printf("(\\n)");
  1975. } else if(c == '\r') {
  1976. printf("(\\r)");
  1977. } else if(c == 0x1b) {
  1978. printf("(\\e)");
  1979. } else {
  1980. printf("(%02x)", c);
  1981. }
  1982. }
  1983. printf("ESC\\\n");
  1984. }
  1985. void
  1986. strreset(void) {
  1987. memset(&strescseq, 0, sizeof(strescseq));
  1988. }
  1989. void
  1990. tprinter(char *s, size_t len) {
  1991. if(iofd != -1 && xwrite(iofd, s, len) < 0) {
  1992. fprintf(stderr, "Error writing in %s:%s\n",
  1993. opt_io, strerror(errno));
  1994. close(iofd);
  1995. iofd = -1;
  1996. }
  1997. }
  1998. void
  1999. toggleprinter(const Arg *arg) {
  2000. term.mode ^= MODE_PRINT;
  2001. }
  2002. void
  2003. printscreen(const Arg *arg) {
  2004. tdump();
  2005. }
  2006. void
  2007. printsel(const Arg *arg) {
  2008. tdumpsel();
  2009. }
  2010. void
  2011. tdumpsel(void) {
  2012. char *ptr;
  2013. if((ptr = getsel())) {
  2014. tprinter(ptr, strlen(ptr));
  2015. free(ptr);
  2016. }
  2017. }
  2018. void
  2019. tdumpline(int n) {
  2020. Glyph *bp, *end;
  2021. bp = &term.line[n][0];
  2022. end = &bp[MIN(tlinelen(n), term.col) - 1];
  2023. if(bp != end || bp->c[0] != ' ') {
  2024. for( ;bp <= end; ++bp)
  2025. tprinter(bp->c, utf8len(bp->c));
  2026. }
  2027. tprinter("\n", 1);
  2028. }
  2029. void
  2030. tdump(void) {
  2031. int i;
  2032. for(i = 0; i < term.row; ++i)
  2033. tdumpline(i);
  2034. }
  2035. void
  2036. tputtab(int n) {
  2037. uint x = term.c.x;
  2038. if(n > 0) {
  2039. while(x < term.col && n--)
  2040. for(++x; x < term.col && !term.tabs[x]; ++x)
  2041. /* nothing */ ;
  2042. } else if(n < 0) {
  2043. while(x > 0 && n++)
  2044. for(--x; x > 0 && !term.tabs[x]; --x)
  2045. /* nothing */ ;
  2046. }
  2047. tmoveto(x, term.c.y);
  2048. }
  2049. void
  2050. techo(char *buf, int len) {
  2051. for(; len > 0; buf++, len--) {
  2052. char c = *buf;
  2053. if(ISCONTROL(c)) { /* control code */
  2054. if(c & 0x80) {
  2055. c &= 0x7f;
  2056. tputc("^", 1);
  2057. tputc("[", 1);
  2058. } else if(c != '\n' && c != '\r' && c != '\t') {
  2059. c ^= '\x40';
  2060. tputc("^", 1);
  2061. }
  2062. tputc(&c, 1);
  2063. } else {
  2064. break;
  2065. }
  2066. }
  2067. if(len)
  2068. tputc(buf, len);
  2069. }
  2070. void
  2071. tdeftran(char ascii) {
  2072. static char cs[] = "0B";
  2073. static int vcs[] = {CS_GRAPHIC0, CS_USA};
  2074. char *p;
  2075. if((p = strchr(cs, ascii)) == NULL) {
  2076. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  2077. } else {
  2078. term.trantbl[term.icharset] = vcs[p - cs];
  2079. }
  2080. }
  2081. void
  2082. tstrsequence(uchar c) {
  2083. if (c & 0x80) {
  2084. switch (c) {
  2085. case 0x90: /* DCS -- Device Control String */
  2086. c = 'P';
  2087. break;
  2088. case 0x9f: /* APC -- Application Program Command */
  2089. c = '_';
  2090. break;
  2091. case 0x9e: /* PM -- Privacy Message */
  2092. c = '^';
  2093. break;
  2094. case 0x9d: /* OSC -- Operating System Command */
  2095. c = ']';
  2096. break;
  2097. }
  2098. }
  2099. strreset();
  2100. strescseq.type = c;
  2101. term.esc |= ESC_STR;
  2102. return;
  2103. }
  2104. void
  2105. tcontrolcode(uchar ascii) {
  2106. static char question[UTF_SIZ] = "?";
  2107. switch(ascii) {
  2108. case '\t': /* HT */
  2109. tputtab(1);
  2110. return;
  2111. case '\b': /* BS */
  2112. tmoveto(term.c.x-1, term.c.y);
  2113. return;
  2114. case '\r': /* CR */
  2115. tmoveto(0, term.c.y);
  2116. return;
  2117. case '\f': /* LF */
  2118. case '\v': /* VT */
  2119. case '\n': /* LF */
  2120. /* go to first col if the mode is set */
  2121. tnewline(IS_SET(MODE_CRLF));
  2122. return;
  2123. case '\a': /* BEL */
  2124. if(term.esc & ESC_STR_END) {
  2125. /* backwards compatibility to xterm */
  2126. strhandle();
  2127. } else {
  2128. if(!(xw.state & WIN_FOCUSED))
  2129. xseturgency(1);
  2130. if (bellvolume)
  2131. XBell(xw.dpy, bellvolume);
  2132. }
  2133. break;
  2134. case '\033': /* ESC */
  2135. csireset();
  2136. term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
  2137. term.esc |= ESC_START;
  2138. return;
  2139. case '\016': /* SO */
  2140. term.charset = 0;
  2141. return;
  2142. case '\017': /* SI */
  2143. term.charset = 1;
  2144. return;
  2145. case '\032': /* SUB */
  2146. tsetchar(question, &term.c.attr, term.c.x, term.c.y);
  2147. case '\030': /* CAN */
  2148. csireset();
  2149. break;
  2150. case '\005': /* ENQ (IGNORED) */
  2151. case '\000': /* NUL (IGNORED) */
  2152. case '\021': /* XON (IGNORED) */
  2153. case '\023': /* XOFF (IGNORED) */
  2154. case 0177: /* DEL (IGNORED) */
  2155. return;
  2156. case 0x84: /* TODO: IND */
  2157. break;
  2158. case 0x85: /* NEL -- Next line */
  2159. tnewline(1); /* always go to first col */
  2160. break;
  2161. case 0x88: /* HTS -- Horizontal tab stop */
  2162. term.tabs[term.c.x] = 1;
  2163. break;
  2164. case 0x8d: /* TODO: RI */
  2165. case 0x8e: /* TODO: SS2 */
  2166. case 0x8f: /* TODO: SS3 */
  2167. case 0x98: /* TODO: SOS */
  2168. break;
  2169. case 0x9a: /* DECID -- Identify Terminal */
  2170. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  2171. break;
  2172. case 0x9b: /* TODO: CSI */
  2173. case 0x9c: /* TODO: ST */
  2174. break;
  2175. case 0x90: /* DCS -- Device Control String */
  2176. case 0x9f: /* APC -- Application Program Command */
  2177. case 0x9e: /* PM -- Privacy Message */
  2178. case 0x9d: /* OSC -- Operating System Command */
  2179. tstrsequence(ascii);
  2180. return;
  2181. }
  2182. /* only CAN, SUB, \a and C1 chars interrupt a sequence */
  2183. term.esc &= ~(ESC_STR_END|ESC_STR);
  2184. return;
  2185. }
  2186. void
  2187. tdectest(char c) {
  2188. static char E[UTF_SIZ] = "E";
  2189. int x, y;
  2190. if(c == '8') { /* DEC screen alignment test. */
  2191. for(x = 0; x < term.col; ++x) {
  2192. for(y = 0; y < term.row; ++y)
  2193. tsetchar(E, &term.c.attr, x, y);
  2194. }
  2195. }
  2196. }
  2197. void
  2198. tputc(char *c, int len) {
  2199. uchar ascii;
  2200. bool control;
  2201. long unicodep;
  2202. int width;
  2203. Glyph *gp;
  2204. if(len == 1) {
  2205. width = 1;
  2206. unicodep = ascii = *c;
  2207. } else {
  2208. utf8decode(c, &unicodep, UTF_SIZ);
  2209. width = wcwidth(unicodep);
  2210. control = ISCONTROLC1(unicodep);
  2211. ascii = unicodep;
  2212. }
  2213. if(IS_SET(MODE_PRINT))
  2214. tprinter(c, len);
  2215. control = ISCONTROL(unicodep);
  2216. /*
  2217. * STR sequence must be checked before anything else
  2218. * because it uses all following characters until it
  2219. * receives a ESC, a SUB, a ST or any other C1 control
  2220. * character.
  2221. */
  2222. if(term.esc & ESC_STR) {
  2223. if(width == 1 &&
  2224. (ascii == '\a' || ascii == 030 ||
  2225. ascii == 032 || ascii == 033 ||
  2226. ISCONTROLC1(unicodep))) {
  2227. term.esc &= ~(ESC_START|ESC_STR);
  2228. term.esc |= ESC_STR_END;
  2229. } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
  2230. memmove(&strescseq.buf[strescseq.len], c, len);
  2231. strescseq.len += len;
  2232. return;
  2233. } else {
  2234. /*
  2235. * Here is a bug in terminals. If the user never sends
  2236. * some code to stop the str or esc command, then st
  2237. * will stop responding. But this is better than
  2238. * silently failing with unknown characters. At least
  2239. * then users will report back.
  2240. *
  2241. * In the case users ever get fixed, here is the code:
  2242. */
  2243. /*
  2244. * term.esc = 0;
  2245. * strhandle();
  2246. */
  2247. return;
  2248. }
  2249. }
  2250. /*
  2251. * Actions of control codes must be performed as soon they arrive
  2252. * because they can be embedded inside a control sequence, and
  2253. * they must not cause conflicts with sequences.
  2254. */
  2255. if(control) {
  2256. tcontrolcode(ascii);
  2257. /*
  2258. * control codes are not shown ever
  2259. */
  2260. return;
  2261. } else if(term.esc & ESC_START) {
  2262. if(term.esc & ESC_CSI) {
  2263. csiescseq.buf[csiescseq.len++] = ascii;
  2264. if(BETWEEN(ascii, 0x40, 0x7E)
  2265. || csiescseq.len >= \
  2266. sizeof(csiescseq.buf)-1) {
  2267. term.esc = 0;
  2268. csiparse();
  2269. csihandle();
  2270. }
  2271. return;
  2272. } else if(term.esc & ESC_ALTCHARSET) {
  2273. tdeftran(ascii);
  2274. } else if(term.esc & ESC_TEST) {
  2275. tdectest(ascii);
  2276. } else {
  2277. switch(ascii) {
  2278. case '[':
  2279. term.esc |= ESC_CSI;
  2280. return;
  2281. case '#':
  2282. term.esc |= ESC_TEST;
  2283. return;
  2284. case 'P': /* DCS -- Device Control String */
  2285. case '_': /* APC -- Application Program Command */
  2286. case '^': /* PM -- Privacy Message */
  2287. case ']': /* OSC -- Operating System Command */
  2288. case 'k': /* old title set compatibility */
  2289. tstrsequence(ascii);
  2290. return;
  2291. case '(': /* set primary charset G0 */
  2292. case ')': /* set secondary charset G1 */
  2293. case '*': /* set tertiary charset G2 */
  2294. case '+': /* set quaternary charset G3 */
  2295. term.icharset = ascii - '(';
  2296. term.esc |= ESC_ALTCHARSET;
  2297. return;
  2298. case 'D': /* IND -- Linefeed */
  2299. if(term.c.y == term.bot) {
  2300. tscrollup(term.top, 1);
  2301. } else {
  2302. tmoveto(term.c.x, term.c.y+1);
  2303. }
  2304. break;
  2305. case 'E': /* NEL -- Next line */
  2306. tnewline(1); /* always go to first col */
  2307. break;
  2308. case 'H': /* HTS -- Horizontal tab stop */
  2309. term.tabs[term.c.x] = 1;
  2310. break;
  2311. case 'M': /* RI -- Reverse index */
  2312. if(term.c.y == term.top) {
  2313. tscrolldown(term.top, 1);
  2314. } else {
  2315. tmoveto(term.c.x, term.c.y-1);
  2316. }
  2317. break;
  2318. case 'Z': /* DECID -- Identify Terminal */
  2319. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  2320. break;
  2321. case 'c': /* RIS -- Reset to inital state */
  2322. treset();
  2323. xresettitle();
  2324. xloadcols();
  2325. break;
  2326. case '=': /* DECPAM -- Application keypad */
  2327. term.mode |= MODE_APPKEYPAD;
  2328. break;
  2329. case '>': /* DECPNM -- Normal keypad */
  2330. term.mode &= ~MODE_APPKEYPAD;
  2331. break;
  2332. case '7': /* DECSC -- Save Cursor */
  2333. tcursor(CURSOR_SAVE);
  2334. break;
  2335. case '8': /* DECRC -- Restore Cursor */
  2336. tcursor(CURSOR_LOAD);
  2337. break;
  2338. case '\\': /* ST -- String Terminator */
  2339. if(term.esc & ESC_STR_END)
  2340. strhandle();
  2341. break;
  2342. default:
  2343. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2344. (uchar) ascii, isprint(ascii)? ascii:'.');
  2345. break;
  2346. }
  2347. }
  2348. term.esc = 0;
  2349. /*
  2350. * All characters which form part of a sequence are not
  2351. * printed
  2352. */
  2353. return;
  2354. }
  2355. if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
  2356. selclear(NULL);
  2357. gp = &term.line[term.c.y][term.c.x];
  2358. if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2359. gp->mode |= ATTR_WRAP;
  2360. tnewline(1);
  2361. }
  2362. if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col)
  2363. memmove(gp+1, gp, (term.col - term.c.x - 1) * sizeof(Glyph));
  2364. if(term.c.x+width > term.col)
  2365. tnewline(1);
  2366. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  2367. if(width == 2) {
  2368. gp->mode |= ATTR_WIDE;
  2369. if(term.c.x+1 < term.col) {
  2370. gp[1].c[0] = '\0';
  2371. gp[1].mode = ATTR_WDUMMY;
  2372. }
  2373. }
  2374. if(term.c.x+width < term.col) {
  2375. tmoveto(term.c.x+width, term.c.y);
  2376. } else {
  2377. term.c.state |= CURSOR_WRAPNEXT;
  2378. }
  2379. }
  2380. int
  2381. tresize(int col, int row) {
  2382. int i;
  2383. int minrow = MIN(row, term.row);
  2384. int mincol = MIN(col, term.col);
  2385. int slide = term.c.y - row + 1;
  2386. bool *bp;
  2387. Line *orig;
  2388. TCursor c;
  2389. if(col < 1 || row < 1)
  2390. return 0;
  2391. /* free unneeded rows */
  2392. i = 0;
  2393. if(slide > 0) {
  2394. /*
  2395. * slide screen to keep cursor where we expect it -
  2396. * tscrollup would work here, but we can optimize to
  2397. * memmove because we're freeing the earlier lines
  2398. */
  2399. for(/* i = 0 */; i < slide; i++) {
  2400. free(term.line[i]);
  2401. free(term.alt[i]);
  2402. }
  2403. memmove(term.line, term.line + slide, row * sizeof(Line));
  2404. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  2405. }
  2406. for(i += row; i < term.row; i++) {
  2407. free(term.line[i]);
  2408. free(term.alt[i]);
  2409. }
  2410. /* resize to new height */
  2411. term.line = xrealloc(term.line, row * sizeof(Line));
  2412. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2413. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2414. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2415. /* resize each row to new width, zero-pad if needed */
  2416. for(i = 0; i < minrow; i++) {
  2417. term.dirty[i] = 1;
  2418. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2419. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2420. }
  2421. /* allocate any new rows */
  2422. for(/* i == minrow */; i < row; i++) {
  2423. term.dirty[i] = 1;
  2424. term.line[i] = xmalloc(col * sizeof(Glyph));
  2425. term.alt[i] = xmalloc(col * sizeof(Glyph));
  2426. }
  2427. if(col > term.col) {
  2428. bp = term.tabs + term.col;
  2429. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2430. while(--bp > term.tabs && !*bp)
  2431. /* nothing */ ;
  2432. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2433. *bp = 1;
  2434. }
  2435. /* update terminal size */
  2436. term.col = col;
  2437. term.row = row;
  2438. /* reset scrolling region */
  2439. tsetscroll(0, row-1);
  2440. /* make use of the LIMIT in tmoveto */
  2441. tmoveto(term.c.x, term.c.y);
  2442. /* Clearing both screens */
  2443. orig = term.line;
  2444. c = term.c;
  2445. do {
  2446. if(mincol < col && 0 < minrow) {
  2447. tclearregion(mincol, 0, col - 1, minrow - 1);
  2448. }
  2449. if(0 < col && minrow < row) {
  2450. tclearregion(0, minrow, col - 1, row - 1);
  2451. }
  2452. tswapscreen();
  2453. tcursor(CURSOR_LOAD);
  2454. } while(orig != term.line);
  2455. term.c = c;
  2456. return (slide > 0);
  2457. }
  2458. void
  2459. xresize(int col, int row) {
  2460. xw.tw = MAX(1, col * xw.cw);
  2461. xw.th = MAX(1, row * xw.ch);
  2462. XFreePixmap(xw.dpy, xw.buf);
  2463. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2464. DefaultDepth(xw.dpy, xw.scr));
  2465. XftDrawChange(xw.draw, xw.buf);
  2466. xclear(0, 0, xw.w, xw.h);
  2467. }
  2468. static inline ushort
  2469. sixd_to_16bit(int x) {
  2470. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  2471. }
  2472. void
  2473. xloadcols(void) {
  2474. int i;
  2475. XRenderColor color = { .alpha = 0xffff };
  2476. static bool loaded;
  2477. Color *cp;
  2478. if(loaded) {
  2479. for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
  2480. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  2481. }
  2482. /* load colors [0-15] and [256-LEN(colorname)] (config.h) */
  2483. for(i = 0; i < LEN(colorname); i++) {
  2484. if(!colorname[i])
  2485. continue;
  2486. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
  2487. die("Could not allocate color '%s'\n", colorname[i]);
  2488. }
  2489. }
  2490. /* load colors [16-231] ; same colors as xterm */
  2491. for(i = 16; i < 6*6*6+16; i++) {
  2492. color.red = sixd_to_16bit( ((i-16)/36)%6 );
  2493. color.green = sixd_to_16bit( ((i-16)/6) %6 );
  2494. color.blue = sixd_to_16bit( ((i-16)/1) %6 );
  2495. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
  2496. die("Could not allocate color %d\n", i);
  2497. }
  2498. /* load colors [232-255] ; grayscale */
  2499. for(; i < 256; i++) {
  2500. color.red = color.green = color.blue = 0x0808 + 0x0a0a * (i-(6*6*6+16));
  2501. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
  2502. die("Could not allocate color %d\n", i);
  2503. }
  2504. loaded = true;
  2505. }
  2506. int
  2507. xsetcolorname(int x, const char *name) {
  2508. XRenderColor color = { .alpha = 0xffff };
  2509. Color ncolor;
  2510. if(!BETWEEN(x, 0, LEN(colorname)))
  2511. return 1;
  2512. if(!name) {
  2513. if(BETWEEN(x, 16, 16 + 215)) { /* 256 color */
  2514. color.red = sixd_to_16bit( ((x-16)/36)%6 );
  2515. color.green = sixd_to_16bit( ((x-16)/6) %6 );
  2516. color.blue = sixd_to_16bit( ((x-16)/1) %6 );
  2517. if(!XftColorAllocValue(xw.dpy, xw.vis,
  2518. xw.cmap, &color, &ncolor)) {
  2519. return 1;
  2520. }
  2521. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  2522. dc.col[x] = ncolor;
  2523. return 0;
  2524. } else if(BETWEEN(x, 16 + 216, 255)) { /* greyscale */
  2525. color.red = color.green = color.blue = \
  2526. 0x0808 + 0x0a0a * (x - (16 + 216));
  2527. if(!XftColorAllocValue(xw.dpy, xw.vis,
  2528. xw.cmap, &color, &ncolor)) {
  2529. return 1;
  2530. }
  2531. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  2532. dc.col[x] = ncolor;
  2533. return 0;
  2534. } else { /* system colors */
  2535. name = colorname[x];
  2536. }
  2537. }
  2538. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &ncolor))
  2539. return 1;
  2540. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  2541. dc.col[x] = ncolor;
  2542. return 0;
  2543. }
  2544. void
  2545. xtermclear(int col1, int row1, int col2, int row2) {
  2546. XftDrawRect(xw.draw,
  2547. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2548. borderpx + col1 * xw.cw,
  2549. borderpx + row1 * xw.ch,
  2550. (col2-col1+1) * xw.cw,
  2551. (row2-row1+1) * xw.ch);
  2552. }
  2553. /*
  2554. * Absolute coordinates.
  2555. */
  2556. void
  2557. xclear(int x1, int y1, int x2, int y2) {
  2558. XftDrawRect(xw.draw,
  2559. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  2560. x1, y1, x2-x1, y2-y1);
  2561. }
  2562. void
  2563. xhints(void) {
  2564. XClassHint class = {opt_class ? opt_class : termname, termname};
  2565. XWMHints wm = {.flags = InputHint, .input = 1};
  2566. XSizeHints *sizeh = NULL;
  2567. sizeh = XAllocSizeHints();
  2568. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2569. sizeh->height = xw.h;
  2570. sizeh->width = xw.w;
  2571. sizeh->height_inc = xw.ch;
  2572. sizeh->width_inc = xw.cw;
  2573. sizeh->base_height = 2 * borderpx;
  2574. sizeh->base_width = 2 * borderpx;
  2575. if(xw.isfixed == True) {
  2576. sizeh->flags |= PMaxSize | PMinSize;
  2577. sizeh->min_width = sizeh->max_width = xw.w;
  2578. sizeh->min_height = sizeh->max_height = xw.h;
  2579. }
  2580. if(xw.gm & (XValue|YValue)) {
  2581. sizeh->flags |= USPosition | PWinGravity;
  2582. sizeh->x = xw.l;
  2583. sizeh->y = xw.t;
  2584. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  2585. }
  2586. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  2587. &class);
  2588. XFree(sizeh);
  2589. }
  2590. int
  2591. xgeommasktogravity(int mask) {
  2592. switch(mask & (XNegative|YNegative)) {
  2593. case 0:
  2594. return NorthWestGravity;
  2595. case XNegative:
  2596. return NorthEastGravity;
  2597. case YNegative:
  2598. return SouthWestGravity;
  2599. }
  2600. return SouthEastGravity;
  2601. }
  2602. int
  2603. xloadfont(Font *f, FcPattern *pattern) {
  2604. FcPattern *match;
  2605. FcResult result;
  2606. match = FcFontMatch(NULL, pattern, &result);
  2607. if(!match)
  2608. return 1;
  2609. if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  2610. FcPatternDestroy(match);
  2611. return 1;
  2612. }
  2613. f->set = NULL;
  2614. f->pattern = FcPatternDuplicate(pattern);
  2615. f->ascent = f->match->ascent;
  2616. f->descent = f->match->descent;
  2617. f->lbearing = 0;
  2618. f->rbearing = f->match->max_advance_width;
  2619. f->height = f->ascent + f->descent;
  2620. f->width = f->lbearing + f->rbearing;
  2621. return 0;
  2622. }
  2623. void
  2624. xloadfonts(char *fontstr, double fontsize) {
  2625. FcPattern *pattern;
  2626. FcResult r_sz, r_psz;
  2627. double fontval;
  2628. float ceilf(float);
  2629. if(fontstr[0] == '-') {
  2630. pattern = XftXlfdParse(fontstr, False, False);
  2631. } else {
  2632. pattern = FcNameParse((FcChar8 *)fontstr);
  2633. }
  2634. if(!pattern)
  2635. die("st: can't open font %s\n", fontstr);
  2636. if(fontsize > 0) {
  2637. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2638. FcPatternDel(pattern, FC_SIZE);
  2639. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2640. usedfontsize = fontsize;
  2641. } else {
  2642. r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2643. r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
  2644. if(r_psz == FcResultMatch) {
  2645. usedfontsize = fontval;
  2646. } else if(r_sz == FcResultMatch) {
  2647. usedfontsize = -1;
  2648. } else {
  2649. /*
  2650. * Default font size is 12, if none given. This is to
  2651. * have a known usedfontsize value.
  2652. */
  2653. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2654. usedfontsize = 12;
  2655. }
  2656. }
  2657. FcConfigSubstitute(0, pattern, FcMatchPattern);
  2658. FcDefaultSubstitute(pattern);
  2659. if(xloadfont(&dc.font, pattern))
  2660. die("st: can't open font %s\n", fontstr);
  2661. if(usedfontsize < 0) {
  2662. FcPatternGetDouble(dc.font.match->pattern,
  2663. FC_PIXEL_SIZE, 0, &fontval);
  2664. usedfontsize = fontval;
  2665. }
  2666. /* Setting character width and height. */
  2667. xw.cw = ceilf(dc.font.width * cwscale);
  2668. xw.ch = ceilf(dc.font.height * chscale);
  2669. FcPatternDel(pattern, FC_SLANT);
  2670. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2671. if(xloadfont(&dc.ifont, pattern))
  2672. die("st: can't open font %s\n", fontstr);
  2673. FcPatternDel(pattern, FC_WEIGHT);
  2674. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2675. if(xloadfont(&dc.ibfont, pattern))
  2676. die("st: can't open font %s\n", fontstr);
  2677. FcPatternDel(pattern, FC_SLANT);
  2678. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  2679. if(xloadfont(&dc.bfont, pattern))
  2680. die("st: can't open font %s\n", fontstr);
  2681. FcPatternDestroy(pattern);
  2682. }
  2683. int
  2684. xloadfontset(Font *f) {
  2685. FcResult result;
  2686. if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
  2687. return 1;
  2688. return 0;
  2689. }
  2690. void
  2691. xunloadfont(Font *f) {
  2692. XftFontClose(xw.dpy, f->match);
  2693. FcPatternDestroy(f->pattern);
  2694. if(f->set)
  2695. FcFontSetDestroy(f->set);
  2696. }
  2697. void
  2698. xunloadfonts(void) {
  2699. /* Free the loaded fonts in the font cache. */
  2700. while(frclen > 0)
  2701. XftFontClose(xw.dpy, frc[--frclen].font);
  2702. xunloadfont(&dc.font);
  2703. xunloadfont(&dc.bfont);
  2704. xunloadfont(&dc.ifont);
  2705. xunloadfont(&dc.ibfont);
  2706. }
  2707. void
  2708. xzoom(const Arg *arg) {
  2709. xunloadfonts();
  2710. xloadfonts(usedfont, usedfontsize + arg->i);
  2711. cresize(0, 0);
  2712. redraw(0);
  2713. xhints();
  2714. }
  2715. void
  2716. xinit(void) {
  2717. XGCValues gcvalues;
  2718. Cursor cursor;
  2719. Window parent;
  2720. pid_t thispid = getpid();
  2721. if(!(xw.dpy = XOpenDisplay(NULL)))
  2722. die("Can't open display\n");
  2723. xw.scr = XDefaultScreen(xw.dpy);
  2724. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2725. /* font */
  2726. if(!FcInit())
  2727. die("Could not init fontconfig.\n");
  2728. usedfont = (opt_font == NULL)? font : opt_font;
  2729. xloadfonts(usedfont, 0);
  2730. /* colors */
  2731. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2732. xloadcols();
  2733. /* adjust fixed window geometry */
  2734. xw.w = 2 * borderpx + term.col * xw.cw;
  2735. xw.h = 2 * borderpx + term.row * xw.ch;
  2736. if(xw.gm & XNegative)
  2737. xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
  2738. if(xw.gm & YNegative)
  2739. xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
  2740. /* Events */
  2741. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  2742. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  2743. xw.attrs.bit_gravity = NorthWestGravity;
  2744. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  2745. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2746. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2747. xw.attrs.colormap = xw.cmap;
  2748. parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
  2749. XRootWindow(xw.dpy, xw.scr);
  2750. xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
  2751. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2752. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  2753. | CWEventMask | CWColormap, &xw.attrs);
  2754. memset(&gcvalues, 0, sizeof(gcvalues));
  2755. gcvalues.graphics_exposures = False;
  2756. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  2757. &gcvalues);
  2758. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2759. DefaultDepth(xw.dpy, xw.scr));
  2760. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  2761. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2762. /* Xft rendering context */
  2763. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2764. /* input methods */
  2765. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2766. XSetLocaleModifiers("@im=local");
  2767. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2768. XSetLocaleModifiers("@im=");
  2769. if((xw.xim = XOpenIM(xw.dpy,
  2770. NULL, NULL, NULL)) == NULL) {
  2771. die("XOpenIM failed. Could not open input"
  2772. " device.\n");
  2773. }
  2774. }
  2775. }
  2776. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2777. | XIMStatusNothing, XNClientWindow, xw.win,
  2778. XNFocusWindow, xw.win, NULL);
  2779. if(xw.xic == NULL)
  2780. die("XCreateIC failed. Could not obtain input method.\n");
  2781. /* white cursor, black outline */
  2782. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2783. XDefineCursor(xw.dpy, xw.win, cursor);
  2784. XRecolorCursor(xw.dpy, cursor,
  2785. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2786. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2787. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2788. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2789. xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
  2790. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2791. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  2792. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  2793. PropModeReplace, (uchar *)&thispid, 1);
  2794. xresettitle();
  2795. XMapWindow(xw.dpy, xw.win);
  2796. xhints();
  2797. XSync(xw.dpy, False);
  2798. }
  2799. void
  2800. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2801. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2802. width = charlen * xw.cw, xp, i;
  2803. int frcflags;
  2804. int u8fl, u8fblen, u8cblen, doesexist;
  2805. char *u8c, *u8fs;
  2806. long unicodep;
  2807. Font *font = &dc.font;
  2808. FcResult fcres;
  2809. FcPattern *fcpattern, *fontpattern;
  2810. FcFontSet *fcsets[] = { NULL };
  2811. FcCharSet *fccharset;
  2812. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  2813. XRenderColor colfg, colbg;
  2814. XRectangle r;
  2815. int oneatatime;
  2816. frcflags = FRC_NORMAL;
  2817. if(base.mode & ATTR_ITALIC) {
  2818. if(base.fg == defaultfg)
  2819. base.fg = defaultitalic;
  2820. font = &dc.ifont;
  2821. frcflags = FRC_ITALIC;
  2822. } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
  2823. if(base.fg == defaultfg)
  2824. base.fg = defaultitalic;
  2825. font = &dc.ibfont;
  2826. frcflags = FRC_ITALICBOLD;
  2827. } else if(base.mode & ATTR_UNDERLINE) {
  2828. if(base.fg == defaultfg)
  2829. base.fg = defaultunderline;
  2830. }
  2831. if(IS_TRUECOL(base.fg)) {
  2832. colfg.alpha = 0xffff;
  2833. colfg.red = TRUERED(base.fg);
  2834. colfg.green = TRUEGREEN(base.fg);
  2835. colfg.blue = TRUEBLUE(base.fg);
  2836. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  2837. fg = &truefg;
  2838. } else {
  2839. fg = &dc.col[base.fg];
  2840. }
  2841. if(IS_TRUECOL(base.bg)) {
  2842. colbg.alpha = 0xffff;
  2843. colbg.green = TRUEGREEN(base.bg);
  2844. colbg.red = TRUERED(base.bg);
  2845. colbg.blue = TRUEBLUE(base.bg);
  2846. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  2847. bg = &truebg;
  2848. } else {
  2849. bg = &dc.col[base.bg];
  2850. }
  2851. if(base.mode & ATTR_BOLD) {
  2852. /*
  2853. * change basic system colors [0-7]
  2854. * to bright system colors [8-15]
  2855. */
  2856. if(BETWEEN(base.fg, 0, 7) && !(base.mode & ATTR_FAINT))
  2857. fg = &dc.col[base.fg + 8];
  2858. if(base.mode & ATTR_ITALIC) {
  2859. font = &dc.ibfont;
  2860. frcflags = FRC_ITALICBOLD;
  2861. } else {
  2862. font = &dc.bfont;
  2863. frcflags = FRC_BOLD;
  2864. }
  2865. }
  2866. if(IS_SET(MODE_REVERSE)) {
  2867. if(fg == &dc.col[defaultfg]) {
  2868. fg = &dc.col[defaultbg];
  2869. } else {
  2870. colfg.red = ~fg->color.red;
  2871. colfg.green = ~fg->color.green;
  2872. colfg.blue = ~fg->color.blue;
  2873. colfg.alpha = fg->color.alpha;
  2874. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  2875. &revfg);
  2876. fg = &revfg;
  2877. }
  2878. if(bg == &dc.col[defaultbg]) {
  2879. bg = &dc.col[defaultfg];
  2880. } else {
  2881. colbg.red = ~bg->color.red;
  2882. colbg.green = ~bg->color.green;
  2883. colbg.blue = ~bg->color.blue;
  2884. colbg.alpha = bg->color.alpha;
  2885. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  2886. &revbg);
  2887. bg = &revbg;
  2888. }
  2889. }
  2890. if(base.mode & ATTR_REVERSE) {
  2891. temp = fg;
  2892. fg = bg;
  2893. bg = temp;
  2894. }
  2895. if(base.mode & ATTR_FAINT && !(base.mode & ATTR_BOLD)) {
  2896. colfg.red = fg->color.red / 2;
  2897. colfg.green = fg->color.green / 2;
  2898. colfg.blue = fg->color.blue / 2;
  2899. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2900. fg = &revfg;
  2901. }
  2902. if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
  2903. fg = bg;
  2904. if(base.mode & ATTR_INVISIBLE)
  2905. fg = bg;
  2906. /* Intelligent cleaning up of the borders. */
  2907. if(x == 0) {
  2908. xclear(0, (y == 0)? 0 : winy, borderpx,
  2909. winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
  2910. }
  2911. if(x + charlen >= term.col) {
  2912. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2913. ((y >= term.row-1)? xw.h : (winy + xw.ch)));
  2914. }
  2915. if(y == 0)
  2916. xclear(winx, 0, winx + width, borderpx);
  2917. if(y == term.row-1)
  2918. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2919. /* Clean up the region we want to draw to. */
  2920. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  2921. /* Set the clip region because Xft is sometimes dirty. */
  2922. r.x = 0;
  2923. r.y = 0;
  2924. r.height = xw.ch;
  2925. r.width = width;
  2926. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  2927. for(xp = winx; bytelen > 0;) {
  2928. /*
  2929. * Search for the range in the to be printed string of glyphs
  2930. * that are in the main font. Then print that range. If
  2931. * some glyph is found that is not in the font, do the
  2932. * fallback dance.
  2933. */
  2934. u8fs = s;
  2935. u8fblen = 0;
  2936. u8fl = 0;
  2937. oneatatime = font->width != xw.cw;
  2938. for(;;) {
  2939. u8c = s;
  2940. u8cblen = utf8decode(s, &unicodep, UTF_SIZ);
  2941. s += u8cblen;
  2942. bytelen -= u8cblen;
  2943. doesexist = XftCharExists(xw.dpy, font->match, unicodep);
  2944. if(doesexist) {
  2945. u8fl++;
  2946. u8fblen += u8cblen;
  2947. if(!oneatatime && bytelen > 0)
  2948. continue;
  2949. }
  2950. if(u8fl > 0) {
  2951. XftDrawStringUtf8(xw.draw, fg,
  2952. font->match, xp,
  2953. winy + font->ascent,
  2954. (FcChar8 *)u8fs,
  2955. u8fblen);
  2956. xp += xw.cw * u8fl;
  2957. }
  2958. break;
  2959. }
  2960. if(doesexist) {
  2961. if(oneatatime)
  2962. continue;
  2963. break;
  2964. }
  2965. /* Search the font cache. */
  2966. for(i = 0; i < frclen; i++) {
  2967. if(XftCharExists(xw.dpy, frc[i].font, unicodep)
  2968. && frc[i].flags == frcflags) {
  2969. break;
  2970. }
  2971. }
  2972. /* Nothing was found. */
  2973. if(i >= frclen) {
  2974. if(!font->set)
  2975. xloadfontset(font);
  2976. fcsets[0] = font->set;
  2977. /*
  2978. * Nothing was found in the cache. Now use
  2979. * some dozen of Fontconfig calls to get the
  2980. * font for one single character.
  2981. *
  2982. * Xft and fontconfig are design failures.
  2983. */
  2984. fcpattern = FcPatternDuplicate(font->pattern);
  2985. fccharset = FcCharSetCreate();
  2986. FcCharSetAddChar(fccharset, unicodep);
  2987. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  2988. fccharset);
  2989. FcPatternAddBool(fcpattern, FC_SCALABLE,
  2990. FcTrue);
  2991. FcConfigSubstitute(0, fcpattern,
  2992. FcMatchPattern);
  2993. FcDefaultSubstitute(fcpattern);
  2994. fontpattern = FcFontSetMatch(0, fcsets,
  2995. FcTrue, fcpattern, &fcres);
  2996. /*
  2997. * Overwrite or create the new cache entry.
  2998. */
  2999. if(frclen >= LEN(frc)) {
  3000. frclen = LEN(frc) - 1;
  3001. XftFontClose(xw.dpy, frc[frclen].font);
  3002. }
  3003. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  3004. fontpattern);
  3005. frc[frclen].flags = frcflags;
  3006. i = frclen;
  3007. frclen++;
  3008. FcPatternDestroy(fcpattern);
  3009. FcCharSetDestroy(fccharset);
  3010. }
  3011. XftDrawStringUtf8(xw.draw, fg, frc[i].font,
  3012. xp, winy + frc[i].font->ascent,
  3013. (FcChar8 *)u8c, u8cblen);
  3014. xp += xw.cw * wcwidth(unicodep);
  3015. }
  3016. /*
  3017. * This is how the loop above actually should be. Why does the
  3018. * application have to care about font details?
  3019. *
  3020. * I have to repeat: Xft and Fontconfig are design failures.
  3021. */
  3022. /*
  3023. XftDrawStringUtf8(xw.draw, fg, font->set, winx,
  3024. winy + font->ascent, (FcChar8 *)s, bytelen);
  3025. */
  3026. if(base.mode & ATTR_UNDERLINE) {
  3027. XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
  3028. width, 1);
  3029. }
  3030. if(base.mode & ATTR_STRUCK) {
  3031. XftDrawRect(xw.draw, fg, winx, winy + 2 * font->ascent / 3,
  3032. width, 1);
  3033. }
  3034. /* Reset clip to none. */
  3035. XftDrawSetClip(xw.draw, 0);
  3036. }
  3037. void
  3038. xdrawcursor(void) {
  3039. static int oldx = 0, oldy = 0;
  3040. int sl, width, curx;
  3041. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
  3042. LIMIT(oldx, 0, term.col-1);
  3043. LIMIT(oldy, 0, term.row-1);
  3044. curx = term.c.x;
  3045. /* adjust position if in dummy */
  3046. if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
  3047. oldx--;
  3048. if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
  3049. curx--;
  3050. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  3051. /* remove the old cursor */
  3052. sl = utf8len(term.line[oldy][oldx].c);
  3053. width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
  3054. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  3055. oldy, width, sl);
  3056. /* draw the new one */
  3057. if(!(IS_SET(MODE_HIDE))) {
  3058. if(xw.state & WIN_FOCUSED) {
  3059. if(IS_SET(MODE_REVERSE)) {
  3060. g.mode |= ATTR_REVERSE;
  3061. g.fg = defaultcs;
  3062. g.bg = defaultfg;
  3063. }
  3064. sl = utf8len(g.c);
  3065. width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
  3066. ? 2 : 1;
  3067. xdraws(g.c, g, term.c.x, term.c.y, width, sl);
  3068. } else {
  3069. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3070. borderpx + curx * xw.cw,
  3071. borderpx + term.c.y * xw.ch,
  3072. xw.cw - 1, 1);
  3073. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3074. borderpx + curx * xw.cw,
  3075. borderpx + term.c.y * xw.ch,
  3076. 1, xw.ch - 1);
  3077. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3078. borderpx + (curx + 1) * xw.cw - 1,
  3079. borderpx + term.c.y * xw.ch,
  3080. 1, xw.ch - 1);
  3081. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3082. borderpx + curx * xw.cw,
  3083. borderpx + (term.c.y + 1) * xw.ch - 1,
  3084. xw.cw, 1);
  3085. }
  3086. oldx = curx, oldy = term.c.y;
  3087. }
  3088. }
  3089. void
  3090. xsettitle(char *p) {
  3091. XTextProperty prop;
  3092. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  3093. &prop);
  3094. XSetWMName(xw.dpy, xw.win, &prop);
  3095. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  3096. XFree(prop.value);
  3097. }
  3098. void
  3099. xresettitle(void) {
  3100. xsettitle(opt_title ? opt_title : "st");
  3101. }
  3102. void
  3103. redraw(int timeout) {
  3104. struct timespec tv = {0, timeout * 1000};
  3105. tfulldirt();
  3106. draw();
  3107. if(timeout > 0) {
  3108. nanosleep(&tv, NULL);
  3109. XSync(xw.dpy, False); /* necessary for a good tput flash */
  3110. }
  3111. }
  3112. void
  3113. draw(void) {
  3114. drawregion(0, 0, term.col, term.row);
  3115. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
  3116. xw.h, 0, 0);
  3117. XSetForeground(xw.dpy, dc.gc,
  3118. dc.col[IS_SET(MODE_REVERSE)?
  3119. defaultfg : defaultbg].pixel);
  3120. }
  3121. void
  3122. drawregion(int x1, int y1, int x2, int y2) {
  3123. int ic, ib, x, y, ox, sl;
  3124. Glyph base, new;
  3125. char buf[DRAW_BUF_SIZ];
  3126. bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
  3127. long unicodep;
  3128. if(!(xw.state & WIN_VISIBLE))
  3129. return;
  3130. for(y = y1; y < y2; y++) {
  3131. if(!term.dirty[y])
  3132. continue;
  3133. xtermclear(0, y, term.col, y);
  3134. term.dirty[y] = 0;
  3135. base = term.line[y][0];
  3136. ic = ib = ox = 0;
  3137. for(x = x1; x < x2; x++) {
  3138. new = term.line[y][x];
  3139. if(new.mode == ATTR_WDUMMY)
  3140. continue;
  3141. if(ena_sel && selected(x, y))
  3142. new.mode ^= ATTR_REVERSE;
  3143. if(ib > 0 && (ATTRCMP(base, new)
  3144. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  3145. xdraws(buf, base, ox, y, ic, ib);
  3146. ic = ib = 0;
  3147. }
  3148. if(ib == 0) {
  3149. ox = x;
  3150. base = new;
  3151. }
  3152. sl = utf8decode(new.c, &unicodep, UTF_SIZ);
  3153. memcpy(buf+ib, new.c, sl);
  3154. ib += sl;
  3155. ic += (new.mode & ATTR_WIDE)? 2 : 1;
  3156. }
  3157. if(ib > 0)
  3158. xdraws(buf, base, ox, y, ic, ib);
  3159. }
  3160. xdrawcursor();
  3161. }
  3162. void
  3163. expose(XEvent *ev) {
  3164. XExposeEvent *e = &ev->xexpose;
  3165. if(xw.state & WIN_REDRAW) {
  3166. if(!e->count)
  3167. xw.state &= ~WIN_REDRAW;
  3168. }
  3169. redraw(0);
  3170. }
  3171. void
  3172. visibility(XEvent *ev) {
  3173. XVisibilityEvent *e = &ev->xvisibility;
  3174. if(e->state == VisibilityFullyObscured) {
  3175. xw.state &= ~WIN_VISIBLE;
  3176. } else if(!(xw.state & WIN_VISIBLE)) {
  3177. /* need a full redraw for next Expose, not just a buf copy */
  3178. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  3179. }
  3180. }
  3181. void
  3182. unmap(XEvent *ev) {
  3183. xw.state &= ~WIN_VISIBLE;
  3184. }
  3185. void
  3186. xsetpointermotion(int set) {
  3187. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  3188. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  3189. }
  3190. void
  3191. xseturgency(int add) {
  3192. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  3193. MODBIT(h->flags, add, XUrgencyHint);
  3194. XSetWMHints(xw.dpy, xw.win, h);
  3195. XFree(h);
  3196. }
  3197. void
  3198. focus(XEvent *ev) {
  3199. XFocusChangeEvent *e = &ev->xfocus;
  3200. if(e->mode == NotifyGrab)
  3201. return;
  3202. if(ev->type == FocusIn) {
  3203. XSetICFocus(xw.xic);
  3204. xw.state |= WIN_FOCUSED;
  3205. xseturgency(0);
  3206. if(IS_SET(MODE_FOCUS))
  3207. ttywrite("\033[I", 3);
  3208. } else {
  3209. XUnsetICFocus(xw.xic);
  3210. xw.state &= ~WIN_FOCUSED;
  3211. if(IS_SET(MODE_FOCUS))
  3212. ttywrite("\033[O", 3);
  3213. }
  3214. }
  3215. static inline bool
  3216. match(uint mask, uint state) {
  3217. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  3218. }
  3219. void
  3220. numlock(const Arg *dummy) {
  3221. term.numlock ^= 1;
  3222. }
  3223. char*
  3224. kmap(KeySym k, uint state) {
  3225. Key *kp;
  3226. int i;
  3227. /* Check for mapped keys out of X11 function keys. */
  3228. for(i = 0; i < LEN(mappedkeys); i++) {
  3229. if(mappedkeys[i] == k)
  3230. break;
  3231. }
  3232. if(i == LEN(mappedkeys)) {
  3233. if((k & 0xFFFF) < 0xFD00)
  3234. return NULL;
  3235. }
  3236. for(kp = key; kp < key + LEN(key); kp++) {
  3237. if(kp->k != k)
  3238. continue;
  3239. if(!match(kp->mask, state))
  3240. continue;
  3241. if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  3242. continue;
  3243. if(term.numlock && kp->appkey == 2)
  3244. continue;
  3245. if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  3246. continue;
  3247. if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
  3248. continue;
  3249. return kp->s;
  3250. }
  3251. return NULL;
  3252. }
  3253. void
  3254. kpress(XEvent *ev) {
  3255. XKeyEvent *e = &ev->xkey;
  3256. KeySym ksym;
  3257. char buf[32], *customkey;
  3258. int len;
  3259. long c;
  3260. Status status;
  3261. Shortcut *bp;
  3262. if(IS_SET(MODE_KBDLOCK))
  3263. return;
  3264. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  3265. /* 1. shortcuts */
  3266. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  3267. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  3268. bp->func(&(bp->arg));
  3269. return;
  3270. }
  3271. }
  3272. /* 2. custom keys from config.h */
  3273. if((customkey = kmap(ksym, e->state))) {
  3274. ttysend(customkey, strlen(customkey));
  3275. return;
  3276. }
  3277. /* 3. composed string from input method */
  3278. if(len == 0)
  3279. return;
  3280. if(len == 1 && e->state & Mod1Mask) {
  3281. if(IS_SET(MODE_8BIT)) {
  3282. if(*buf < 0177) {
  3283. c = *buf | 0x80;
  3284. len = utf8encode(c, buf, UTF_SIZ);
  3285. }
  3286. } else {
  3287. buf[1] = buf[0];
  3288. buf[0] = '\033';
  3289. len = 2;
  3290. }
  3291. }
  3292. ttysend(buf, len);
  3293. }
  3294. void
  3295. cmessage(XEvent *e) {
  3296. /*
  3297. * See xembed specs
  3298. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  3299. */
  3300. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  3301. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  3302. xw.state |= WIN_FOCUSED;
  3303. xseturgency(0);
  3304. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  3305. xw.state &= ~WIN_FOCUSED;
  3306. }
  3307. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  3308. /* Send SIGHUP to shell */
  3309. kill(pid, SIGHUP);
  3310. exit(EXIT_SUCCESS);
  3311. }
  3312. }
  3313. void
  3314. cresize(int width, int height) {
  3315. int col, row;
  3316. if(width != 0)
  3317. xw.w = width;
  3318. if(height != 0)
  3319. xw.h = height;
  3320. col = (xw.w - 2 * borderpx) / xw.cw;
  3321. row = (xw.h - 2 * borderpx) / xw.ch;
  3322. tresize(col, row);
  3323. xresize(col, row);
  3324. ttyresize();
  3325. }
  3326. void
  3327. resize(XEvent *e) {
  3328. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  3329. return;
  3330. cresize(e->xconfigure.width, e->xconfigure.height);
  3331. }
  3332. void
  3333. run(void) {
  3334. XEvent ev;
  3335. int w = xw.w, h = xw.h;
  3336. fd_set rfd;
  3337. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  3338. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  3339. long deltatime;
  3340. /* Waiting for window mapping */
  3341. while(1) {
  3342. XNextEvent(xw.dpy, &ev);
  3343. if(XFilterEvent(&ev, None))
  3344. continue;
  3345. if(ev.type == ConfigureNotify) {
  3346. w = ev.xconfigure.width;
  3347. h = ev.xconfigure.height;
  3348. } else if(ev.type == MapNotify) {
  3349. break;
  3350. }
  3351. }
  3352. ttynew();
  3353. cresize(w, h);
  3354. clock_gettime(CLOCK_MONOTONIC, &last);
  3355. lastblink = last;
  3356. for(xev = actionfps;;) {
  3357. FD_ZERO(&rfd);
  3358. FD_SET(cmdfd, &rfd);
  3359. FD_SET(xfd, &rfd);
  3360. if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  3361. if(errno == EINTR)
  3362. continue;
  3363. die("select failed: %s\n", strerror(errno));
  3364. }
  3365. if(FD_ISSET(cmdfd, &rfd)) {
  3366. ttyread();
  3367. if(blinktimeout) {
  3368. blinkset = tattrset(ATTR_BLINK);
  3369. if(!blinkset)
  3370. MODBIT(term.mode, 0, MODE_BLINK);
  3371. }
  3372. }
  3373. if(FD_ISSET(xfd, &rfd))
  3374. xev = actionfps;
  3375. clock_gettime(CLOCK_MONOTONIC, &now);
  3376. drawtimeout.tv_sec = 0;
  3377. drawtimeout.tv_nsec = (1000/xfps) * 1E6;
  3378. tv = &drawtimeout;
  3379. dodraw = 0;
  3380. if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  3381. tsetdirtattr(ATTR_BLINK);
  3382. term.mode ^= MODE_BLINK;
  3383. lastblink = now;
  3384. dodraw = 1;
  3385. }
  3386. deltatime = TIMEDIFF(now, last);
  3387. if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
  3388. || deltatime < 0) {
  3389. dodraw = 1;
  3390. last = now;
  3391. }
  3392. if(dodraw) {
  3393. while(XPending(xw.dpy)) {
  3394. XNextEvent(xw.dpy, &ev);
  3395. if(XFilterEvent(&ev, None))
  3396. continue;
  3397. if(handler[ev.type])
  3398. (handler[ev.type])(&ev);
  3399. }
  3400. draw();
  3401. XFlush(xw.dpy);
  3402. if(xev && !FD_ISSET(xfd, &rfd))
  3403. xev--;
  3404. if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  3405. if(blinkset) {
  3406. if(TIMEDIFF(now, lastblink) \
  3407. > blinktimeout) {
  3408. drawtimeout.tv_nsec = 1000;
  3409. } else {
  3410. drawtimeout.tv_nsec = (1E6 * \
  3411. (blinktimeout - \
  3412. TIMEDIFF(now,
  3413. lastblink)));
  3414. }
  3415. } else {
  3416. tv = NULL;
  3417. }
  3418. }
  3419. }
  3420. }
  3421. }
  3422. void
  3423. usage(void) {
  3424. die("%s " VERSION " (c) 2010-2014 st engineers\n" \
  3425. "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
  3426. " [-t title] [-w windowid] [-e command ...]\n", argv0);
  3427. }
  3428. int
  3429. main(int argc, char *argv[]) {
  3430. char *titles;
  3431. uint cols = 80, rows = 24;
  3432. xw.l = xw.t = 0;
  3433. xw.isfixed = False;
  3434. ARGBEGIN {
  3435. case 'a':
  3436. allowaltscreen = false;
  3437. break;
  3438. case 'c':
  3439. opt_class = EARGF(usage());
  3440. break;
  3441. case 'e':
  3442. /* eat all remaining arguments */
  3443. if(argc > 1) {
  3444. opt_cmd = &argv[1];
  3445. if(argv[1] != NULL && opt_title == NULL) {
  3446. titles = xstrdup(argv[1]);
  3447. opt_title = basename(titles);
  3448. }
  3449. }
  3450. goto run;
  3451. case 'f':
  3452. opt_font = EARGF(usage());
  3453. break;
  3454. case 'g':
  3455. xw.gm = XParseGeometry(EARGF(usage()),
  3456. &xw.l, &xw.t, &cols, &rows);
  3457. break;
  3458. case 'i':
  3459. xw.isfixed = True;
  3460. break;
  3461. case 'o':
  3462. opt_io = EARGF(usage());
  3463. break;
  3464. case 't':
  3465. opt_title = EARGF(usage());
  3466. break;
  3467. case 'w':
  3468. opt_embed = EARGF(usage());
  3469. break;
  3470. case 'v':
  3471. default:
  3472. usage();
  3473. } ARGEND;
  3474. run:
  3475. setlocale(LC_CTYPE, "");
  3476. XSetLocaleModifiers("");
  3477. tnew(cols? cols : 1, rows? rows : 1);
  3478. xinit();
  3479. selinit();
  3480. run();
  3481. return 0;
  3482. }