st.c 74 KB

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