st.c 74 KB

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