st.c 79 KB

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