st.c 74 KB

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