st.c 90 KB

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