st.c 86 KB

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