st.c 74 KB

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