st.c 93 KB

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