st.c 71 KB

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