st.c 78 KB

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