st.c 86 KB

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