st.c 80 KB

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