st.c 90 KB

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