st.c 73 KB

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