st.c 73 KB

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