st.c 88 KB

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