st.c 73 KB

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