st.c 73 KB

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