st.c 60 KB

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