st.c 85 KB

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