st.c 74 KB

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