st.c 87 KB

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