st.c 96 KB

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