st.c 90 KB

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