st.c 74 KB

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