st.c 63 KB

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