st.c 87 KB

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