st.c 61 KB

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