st.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766
  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. 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));
  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));
  1741. break;
  1742. case 'c': /* RIS -- Reset to inital state */
  1743. treset();
  1744. term.esc = 0;
  1745. xresettitle();
  1746. break;
  1747. case '=': /* DECPAM -- Application keypad */
  1748. term.mode |= MODE_APPKEYPAD;
  1749. term.esc = 0;
  1750. break;
  1751. case '>': /* DECPNM -- Normal keypad */
  1752. term.mode &= ~MODE_APPKEYPAD;
  1753. term.esc = 0;
  1754. break;
  1755. case '7': /* DECSC -- Save Cursor */
  1756. tcursor(CURSOR_SAVE);
  1757. term.esc = 0;
  1758. break;
  1759. case '8': /* DECRC -- Restore Cursor */
  1760. tcursor(CURSOR_LOAD);
  1761. term.esc = 0;
  1762. break;
  1763. case '\\': /* ST -- Stop */
  1764. term.esc = 0;
  1765. break;
  1766. default:
  1767. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1768. (uchar) ascii, isprint(ascii)? ascii:'.');
  1769. term.esc = 0;
  1770. }
  1771. }
  1772. /*
  1773. * All characters which forms part of a sequence are not
  1774. * printed
  1775. */
  1776. return;
  1777. }
  1778. /*
  1779. * Display control codes only if we are in graphic mode
  1780. */
  1781. if(control && !(term.c.attr.mode & ATTR_GFX))
  1782. return;
  1783. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1784. sel.bx = -1;
  1785. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1786. tnewline(1); /* always go to first col */
  1787. tsetchar(c);
  1788. if(term.c.x+1 < term.col)
  1789. tmoveto(term.c.x+1, term.c.y);
  1790. else
  1791. term.c.state |= CURSOR_WRAPNEXT;
  1792. }
  1793. int
  1794. tresize(int col, int row) {
  1795. int i, x;
  1796. int minrow = MIN(row, term.row);
  1797. int mincol = MIN(col, term.col);
  1798. int slide = term.c.y - row + 1;
  1799. bool *bp;
  1800. if(col < 1 || row < 1)
  1801. return 0;
  1802. /* free unneeded rows */
  1803. i = 0;
  1804. if(slide > 0) {
  1805. /* slide screen to keep cursor where we expect it -
  1806. * tscrollup would work here, but we can optimize to
  1807. * memmove because we're freeing the earlier lines */
  1808. for(/* i = 0 */; i < slide; i++) {
  1809. free(term.line[i]);
  1810. free(term.alt[i]);
  1811. }
  1812. memmove(term.line, term.line + slide, row * sizeof(Line));
  1813. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1814. }
  1815. for(i += row; i < term.row; i++) {
  1816. free(term.line[i]);
  1817. free(term.alt[i]);
  1818. }
  1819. /* resize to new height */
  1820. term.line = xrealloc(term.line, row * sizeof(Line));
  1821. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1822. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1823. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1824. /* resize each row to new width, zero-pad if needed */
  1825. for(i = 0; i < minrow; i++) {
  1826. term.dirty[i] = 1;
  1827. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1828. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1829. for(x = mincol; x < col; x++) {
  1830. term.line[i][x].state = 0;
  1831. term.alt[i][x].state = 0;
  1832. }
  1833. }
  1834. /* allocate any new rows */
  1835. for(/* i == minrow */; i < row; i++) {
  1836. term.dirty[i] = 1;
  1837. term.line[i] = xcalloc(col, sizeof(Glyph));
  1838. term.alt [i] = xcalloc(col, sizeof(Glyph));
  1839. }
  1840. if(col > term.col) {
  1841. bp = term.tabs + term.col;
  1842. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1843. while(--bp > term.tabs && !*bp)
  1844. /* nothing */ ;
  1845. for(bp += TAB; bp < term.tabs + col; bp += TAB)
  1846. *bp = 1;
  1847. }
  1848. /* update terminal size */
  1849. term.col = col, term.row = row;
  1850. /* make use of the LIMIT in tmoveto */
  1851. tmoveto(term.c.x, term.c.y);
  1852. /* reset scrolling region */
  1853. tsetscroll(0, row-1);
  1854. return (slide > 0);
  1855. }
  1856. void
  1857. xresize(int col, int row) {
  1858. xw.tw = MAX(1, 2*BORDER + col * xw.cw);
  1859. xw.th = MAX(1, 2*BORDER + row * xw.ch);
  1860. XftDrawChange(xw.xft_draw, xw.buf);
  1861. }
  1862. void
  1863. xloadcols(void) {
  1864. int i, r, g, b;
  1865. XRenderColor xft_color = { .alpha = 0 };
  1866. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1867. for(i = 0; i < LEN(colorname); i++) {
  1868. if(!colorname[i])
  1869. continue;
  1870. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
  1871. die("Could not allocate color '%s'\n", colorname[i]);
  1872. }
  1873. }
  1874. /* load colors [16-255] ; same colors as xterm */
  1875. for(i = 16, r = 0; r < 6; r++) {
  1876. for(g = 0; g < 6; g++) {
  1877. for(b = 0; b < 6; b++) {
  1878. xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1879. xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1880. xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1881. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
  1882. die("Could not allocate color %d\n", i);
  1883. }
  1884. i++;
  1885. }
  1886. }
  1887. }
  1888. for(r = 0; r < 24; r++, i++) {
  1889. xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
  1890. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
  1891. &dc.xft_col[i])) {
  1892. die("Could not allocate color %d\n", i);
  1893. }
  1894. }
  1895. }
  1896. void
  1897. xtermclear(int col1, int row1, int col2, int row2) {
  1898. XftDrawRect(xw.xft_draw,
  1899. &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
  1900. BORDER + col1 * xw.cw,
  1901. BORDER + row1 * xw.ch,
  1902. (col2-col1+1) * xw.cw,
  1903. (row2-row1+1) * xw.ch);
  1904. }
  1905. /*
  1906. * Absolute coordinates.
  1907. */
  1908. void
  1909. xclear(int x1, int y1, int x2, int y2) {
  1910. XftDrawRect(xw.xft_draw,
  1911. &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
  1912. x1, y1, x2-x1, y2-y1);
  1913. }
  1914. void
  1915. xhints(void) {
  1916. XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
  1917. XWMHints wm = {.flags = InputHint, .input = 1};
  1918. XSizeHints *sizeh = NULL;
  1919. sizeh = XAllocSizeHints();
  1920. if(xw.isfixed == False) {
  1921. sizeh->flags = PSize | PResizeInc | PBaseSize;
  1922. sizeh->height = xw.h;
  1923. sizeh->width = xw.w;
  1924. sizeh->height_inc = xw.ch;
  1925. sizeh->width_inc = xw.cw;
  1926. sizeh->base_height = 2*BORDER;
  1927. sizeh->base_width = 2*BORDER;
  1928. } else {
  1929. sizeh->flags = PMaxSize | PMinSize;
  1930. sizeh->min_width = sizeh->max_width = xw.fw;
  1931. sizeh->min_height = sizeh->max_height = xw.fh;
  1932. }
  1933. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  1934. XFree(sizeh);
  1935. }
  1936. void
  1937. xinitfont(Font *f, char *fontstr) {
  1938. FcPattern *pattern, *match;
  1939. FcResult result;
  1940. pattern = FcNameParse((FcChar8 *)fontstr);
  1941. if(!pattern)
  1942. die("st: can't open font %s\n", fontstr);
  1943. match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
  1944. FcPatternDestroy(pattern);
  1945. if(!match)
  1946. die("st: can't open font %s\n", fontstr);
  1947. if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
  1948. FcPatternDestroy(match);
  1949. die("st: can't open font %s.\n", fontstr);
  1950. }
  1951. f->ascent = f->xft_set->ascent;
  1952. f->descent = f->xft_set->descent;
  1953. f->lbearing = 0;
  1954. f->rbearing = f->xft_set->max_advance_width;
  1955. f->height = f->xft_set->height;
  1956. f->width = f->lbearing + f->rbearing;
  1957. }
  1958. void
  1959. initfonts(char *fontstr) {
  1960. char *fstr;
  1961. xinitfont(&dc.font, fontstr);
  1962. xw.cw = dc.font.width;
  1963. xw.ch = dc.font.height;
  1964. fstr = smstrcat(fontstr, ":weight=bold", NULL);
  1965. xinitfont(&dc.bfont, fstr);
  1966. free(fstr);
  1967. fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
  1968. xinitfont(&dc.ifont, fstr);
  1969. free(fstr);
  1970. fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
  1971. xinitfont(&dc.ibfont, fstr);
  1972. free(fstr);
  1973. }
  1974. void
  1975. xinit(void) {
  1976. XSetWindowAttributes attrs;
  1977. Cursor cursor;
  1978. Window parent;
  1979. int sw, sh, major, minor;
  1980. if(!(xw.dpy = XOpenDisplay(NULL)))
  1981. die("Can't open display\n");
  1982. xw.scr = XDefaultScreen(xw.dpy);
  1983. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  1984. /* font */
  1985. initfonts((opt_font != NULL)? opt_font : FONT);
  1986. /* colors */
  1987. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  1988. xloadcols();
  1989. /* adjust fixed window geometry */
  1990. if(xw.isfixed) {
  1991. sw = DisplayWidth(xw.dpy, xw.scr);
  1992. sh = DisplayHeight(xw.dpy, xw.scr);
  1993. if(xw.fx < 0)
  1994. xw.fx = sw + xw.fx - xw.fw - 1;
  1995. if(xw.fy < 0)
  1996. xw.fy = sh + xw.fy - xw.fh - 1;
  1997. xw.h = xw.fh;
  1998. xw.w = xw.fw;
  1999. } else {
  2000. /* window - default size */
  2001. xw.h = 2*BORDER + term.row * xw.ch;
  2002. xw.w = 2*BORDER + term.col * xw.cw;
  2003. xw.fx = 0;
  2004. xw.fy = 0;
  2005. }
  2006. attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
  2007. attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
  2008. attrs.bit_gravity = NorthWestGravity;
  2009. attrs.event_mask = FocusChangeMask | KeyPressMask
  2010. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2011. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2012. attrs.colormap = xw.cmap;
  2013. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  2014. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  2015. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2016. xw.vis,
  2017. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  2018. | CWColormap,
  2019. &attrs);
  2020. /* double buffering */
  2021. if(!XdbeQueryExtension(xw.dpy, &major, &minor))
  2022. die("Xdbe extension is not present\n");
  2023. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  2024. /* Xft rendering context */
  2025. xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2026. /* input methods */
  2027. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  2028. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2029. | XIMStatusNothing, XNClientWindow, xw.win,
  2030. XNFocusWindow, xw.win, NULL);
  2031. /* gc */
  2032. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  2033. /* white cursor, black outline */
  2034. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2035. XDefineCursor(xw.dpy, xw.win, cursor);
  2036. XRecolorCursor(xw.dpy, cursor,
  2037. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2038. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2039. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2040. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2041. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2042. xresettitle();
  2043. XMapWindow(xw.dpy, xw.win);
  2044. xhints();
  2045. XSync(xw.dpy, 0);
  2046. }
  2047. void
  2048. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2049. int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
  2050. width = charlen * xw.cw;
  2051. Font *font = &dc.font;
  2052. XGlyphInfo extents;
  2053. XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
  2054. *temp, revfg, revbg;
  2055. XRenderColor colfg, colbg;
  2056. if(base.mode & ATTR_REVERSE)
  2057. temp = fg, fg = bg, bg = temp;
  2058. if(base.mode & ATTR_BOLD) {
  2059. if(BETWEEN(base.fg, 0, 7)) {
  2060. /* basic system colors */
  2061. fg = &dc.xft_col[base.fg + 8];
  2062. } else if(BETWEEN(base.fg, 16, 195)) {
  2063. /* 256 colors */
  2064. fg = &dc.xft_col[base.fg + 36];
  2065. } else if(BETWEEN(base.fg, 232, 251)) {
  2066. /* greyscale */
  2067. fg = &dc.xft_col[base.fg + 4];
  2068. }
  2069. /*
  2070. * Those ranges will not be brightened:
  2071. * 8 - 15 – bright system colors
  2072. * 196 - 231 – highest 256 color cube
  2073. * 252 - 255 – brightest colors in greyscale
  2074. */
  2075. font = &dc.bfont;
  2076. }
  2077. if(base.mode & ATTR_ITALIC)
  2078. font = &dc.ifont;
  2079. if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
  2080. font = &dc.ibfont;
  2081. if(IS_SET(MODE_REVERSE)) {
  2082. if(fg == &dc.xft_col[DefaultFG]) {
  2083. fg = &dc.xft_col[DefaultBG];
  2084. } else {
  2085. colfg.red = ~fg->color.red;
  2086. colfg.green = ~fg->color.green;
  2087. colfg.blue = ~fg->color.blue;
  2088. colfg.alpha = fg->color.alpha;
  2089. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2090. fg = &revfg;
  2091. }
  2092. if(bg == &dc.xft_col[DefaultBG]) {
  2093. bg = &dc.xft_col[DefaultFG];
  2094. } else {
  2095. colbg.red = ~bg->color.red;
  2096. colbg.green = ~bg->color.green;
  2097. colbg.blue = ~bg->color.blue;
  2098. colbg.alpha = bg->color.alpha;
  2099. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
  2100. bg = &revbg;
  2101. }
  2102. }
  2103. XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
  2104. &extents);
  2105. width = extents.xOff;
  2106. /* Intelligent cleaning up of the borders. */
  2107. if(x == 0) {
  2108. xclear(0, (y == 0)? 0 : winy, BORDER,
  2109. winy + xw.ch + (y == term.row-1)? xw.h : 0);
  2110. }
  2111. if(x + charlen >= term.col-1) {
  2112. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2113. (y == term.row-1)? xw.h : (winy + xw.ch));
  2114. }
  2115. if(y == 0)
  2116. xclear(winx, 0, winx + width, BORDER);
  2117. if(y == term.row-1)
  2118. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2119. XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
  2120. XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
  2121. winy + font->ascent, (FcChar8 *)s, bytelen);
  2122. if(base.mode & ATTR_UNDERLINE) {
  2123. XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
  2124. width, 1);
  2125. }
  2126. }
  2127. void
  2128. xdrawcursor(void) {
  2129. static int oldx = 0, oldy = 0;
  2130. int sl;
  2131. Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
  2132. LIMIT(oldx, 0, term.col-1);
  2133. LIMIT(oldy, 0, term.row-1);
  2134. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  2135. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  2136. /* remove the old cursor */
  2137. if(term.line[oldy][oldx].state & GLYPH_SET) {
  2138. sl = utf8size(term.line[oldy][oldx].c);
  2139. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  2140. oldy, 1, sl);
  2141. } else {
  2142. xtermclear(oldx, oldy, oldx, oldy);
  2143. }
  2144. /* draw the new one */
  2145. if(!(term.c.state & CURSOR_HIDE)) {
  2146. if(!(xw.state & WIN_FOCUSED))
  2147. g.bg = DefaultUCS;
  2148. if(IS_SET(MODE_REVERSE))
  2149. g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
  2150. sl = utf8size(g.c);
  2151. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  2152. oldx = term.c.x, oldy = term.c.y;
  2153. }
  2154. }
  2155. void
  2156. xresettitle(void) {
  2157. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  2158. }
  2159. void
  2160. redraw(void) {
  2161. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  2162. tfulldirt();
  2163. draw();
  2164. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2165. nanosleep(&tv, NULL);
  2166. }
  2167. void
  2168. draw(void) {
  2169. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  2170. drawregion(0, 0, term.col, term.row);
  2171. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  2172. }
  2173. void
  2174. drawregion(int x1, int y1, int x2, int y2) {
  2175. int ic, ib, x, y, ox, sl;
  2176. Glyph base, new;
  2177. char buf[DRAW_BUF_SIZ];
  2178. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
  2179. if((sel.alt && !alt) || (!sel.alt && alt))
  2180. ena_sel = 0;
  2181. if(!(xw.state & WIN_VISIBLE))
  2182. return;
  2183. for(y = y1; y < y2; y++) {
  2184. if(!term.dirty[y])
  2185. continue;
  2186. xtermclear(0, y, term.col, y);
  2187. term.dirty[y] = 0;
  2188. base = term.line[y][0];
  2189. ic = ib = ox = 0;
  2190. for(x = x1; x < x2; x++) {
  2191. new = term.line[y][x];
  2192. if(ena_sel && *(new.c) && selected(x, y))
  2193. new.mode ^= ATTR_REVERSE;
  2194. if(ib > 0 && (!(new.state & GLYPH_SET)
  2195. || ATTRCMP(base, new)
  2196. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  2197. xdraws(buf, base, ox, y, ic, ib);
  2198. ic = ib = 0;
  2199. }
  2200. if(new.state & GLYPH_SET) {
  2201. if(ib == 0) {
  2202. ox = x;
  2203. base = new;
  2204. }
  2205. sl = utf8size(new.c);
  2206. memcpy(buf+ib, new.c, sl);
  2207. ib += sl;
  2208. ++ic;
  2209. }
  2210. }
  2211. if(ib > 0)
  2212. xdraws(buf, base, ox, y, ic, ib);
  2213. }
  2214. xdrawcursor();
  2215. }
  2216. void
  2217. expose(XEvent *ev) {
  2218. XExposeEvent *e = &ev->xexpose;
  2219. if(xw.state & WIN_REDRAW) {
  2220. if(!e->count)
  2221. xw.state &= ~WIN_REDRAW;
  2222. }
  2223. }
  2224. void
  2225. visibility(XEvent *ev) {
  2226. XVisibilityEvent *e = &ev->xvisibility;
  2227. if(e->state == VisibilityFullyObscured) {
  2228. xw.state &= ~WIN_VISIBLE;
  2229. } else if(!(xw.state & WIN_VISIBLE)) {
  2230. /* need a full redraw for next Expose, not just a buf copy */
  2231. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2232. }
  2233. }
  2234. void
  2235. unmap(XEvent *ev) {
  2236. xw.state &= ~WIN_VISIBLE;
  2237. }
  2238. void
  2239. xseturgency(int add) {
  2240. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2241. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2242. XSetWMHints(xw.dpy, xw.win, h);
  2243. XFree(h);
  2244. }
  2245. void
  2246. focus(XEvent *ev) {
  2247. if(ev->type == FocusIn) {
  2248. xw.state |= WIN_FOCUSED;
  2249. xseturgency(0);
  2250. } else {
  2251. xw.state &= ~WIN_FOCUSED;
  2252. }
  2253. }
  2254. char*
  2255. kmap(KeySym k, uint state) {
  2256. int i;
  2257. uint mask;
  2258. state &= ~Mod2Mask;
  2259. for(i = 0; i < LEN(key); i++) {
  2260. mask = key[i].mask;
  2261. if(key[i].k == k && ((state & mask) == mask
  2262. || (mask == XK_NO_MOD && !state))) {
  2263. return (char*)key[i].s;
  2264. }
  2265. }
  2266. return NULL;
  2267. }
  2268. void
  2269. kpress(XEvent *ev) {
  2270. XKeyEvent *e = &ev->xkey;
  2271. KeySym ksym;
  2272. char buf[32];
  2273. char *customkey;
  2274. int len;
  2275. int meta;
  2276. int shift;
  2277. Status status;
  2278. if (IS_SET(MODE_KBDLOCK))
  2279. return;
  2280. meta = e->state & Mod1Mask;
  2281. shift = e->state & ShiftMask;
  2282. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  2283. /* 1. custom keys from config.h */
  2284. if((customkey = kmap(ksym, e->state))) {
  2285. ttywrite(customkey, strlen(customkey));
  2286. /* 2. hardcoded (overrides X lookup) */
  2287. } else {
  2288. switch(ksym) {
  2289. case XK_Up:
  2290. case XK_Down:
  2291. case XK_Left:
  2292. case XK_Right:
  2293. /* XXX: shift up/down doesn't work */
  2294. sprintf(buf, "\033%c%c",
  2295. IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
  2296. (shift ? "dacb":"DACB")[ksym - XK_Left]);
  2297. ttywrite(buf, 3);
  2298. break;
  2299. case XK_Insert:
  2300. if(shift)
  2301. selpaste();
  2302. break;
  2303. case XK_Return:
  2304. if(IS_SET(MODE_CRLF)) {
  2305. ttywrite("\r\n", 2);
  2306. } else {
  2307. ttywrite("\r", 1);
  2308. }
  2309. break;
  2310. /* 3. X lookup */
  2311. default:
  2312. if(len > 0) {
  2313. if(meta && len == 1)
  2314. ttywrite("\033", 1);
  2315. ttywrite(buf, len);
  2316. }
  2317. break;
  2318. }
  2319. }
  2320. }
  2321. void
  2322. cmessage(XEvent *e) {
  2323. /* See xembed specs
  2324. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2325. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2326. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2327. xw.state |= WIN_FOCUSED;
  2328. xseturgency(0);
  2329. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2330. xw.state &= ~WIN_FOCUSED;
  2331. }
  2332. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  2333. /* Send SIGHUP to shell */
  2334. kill(pid, SIGHUP);
  2335. exit(EXIT_SUCCESS);
  2336. }
  2337. }
  2338. void
  2339. resize(XEvent *e) {
  2340. int col, row;
  2341. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2342. return;
  2343. xw.w = e->xconfigure.width;
  2344. xw.h = e->xconfigure.height;
  2345. col = (xw.w - 2*BORDER) / xw.cw;
  2346. row = (xw.h - 2*BORDER) / xw.ch;
  2347. if(col == term.col && row == term.row)
  2348. return;
  2349. tresize(col, row);
  2350. xresize(col, row);
  2351. ttyresize();
  2352. }
  2353. void
  2354. run(void) {
  2355. XEvent ev;
  2356. fd_set rfd;
  2357. int xfd = XConnectionNumber(xw.dpy), i;
  2358. struct timeval drawtimeout, *tv = NULL;
  2359. for(i = 0;; i++) {
  2360. FD_ZERO(&rfd);
  2361. FD_SET(cmdfd, &rfd);
  2362. FD_SET(xfd, &rfd);
  2363. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  2364. if(errno == EINTR)
  2365. continue;
  2366. die("select failed: %s\n", SERRNO);
  2367. }
  2368. /*
  2369. * Stop after a certain number of reads so the user does not
  2370. * feel like the system is stuttering.
  2371. */
  2372. if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
  2373. ttyread();
  2374. /*
  2375. * Just wait a bit so it isn't disturbing the
  2376. * user and the system is able to write something.
  2377. */
  2378. drawtimeout.tv_sec = 0;
  2379. drawtimeout.tv_usec = 5;
  2380. tv = &drawtimeout;
  2381. continue;
  2382. }
  2383. i = 0;
  2384. tv = NULL;
  2385. while(XPending(xw.dpy)) {
  2386. XNextEvent(xw.dpy, &ev);
  2387. if(XFilterEvent(&ev, xw.win))
  2388. continue;
  2389. if(handler[ev.type])
  2390. (handler[ev.type])(&ev);
  2391. }
  2392. draw();
  2393. XFlush(xw.dpy);
  2394. }
  2395. }
  2396. int
  2397. main(int argc, char *argv[]) {
  2398. int i, bitm, xr, yr;
  2399. uint wr, hr;
  2400. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2401. xw.isfixed = False;
  2402. for(i = 1; i < argc; i++) {
  2403. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2404. case 'c':
  2405. if(++i < argc)
  2406. opt_class = argv[i];
  2407. break;
  2408. case 'e':
  2409. /* eat every remaining arguments */
  2410. if(++i < argc)
  2411. opt_cmd = &argv[i];
  2412. goto run;
  2413. case 'f':
  2414. if(++i < argc)
  2415. opt_font = argv[i];
  2416. break;
  2417. case 'g':
  2418. if(++i >= argc)
  2419. break;
  2420. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2421. if(bitm & XValue)
  2422. xw.fx = xr;
  2423. if(bitm & YValue)
  2424. xw.fy = yr;
  2425. if(bitm & WidthValue)
  2426. xw.fw = (int)wr;
  2427. if(bitm & HeightValue)
  2428. xw.fh = (int)hr;
  2429. if(bitm & XNegative && xw.fx == 0)
  2430. xw.fx = -1;
  2431. if(bitm & XNegative && xw.fy == 0)
  2432. xw.fy = -1;
  2433. if(xw.fh != 0 && xw.fw != 0)
  2434. xw.isfixed = True;
  2435. break;
  2436. case 'o':
  2437. if(++i < argc)
  2438. opt_io = argv[i];
  2439. break;
  2440. case 't':
  2441. if(++i < argc)
  2442. opt_title = argv[i];
  2443. break;
  2444. case 'v':
  2445. default:
  2446. die(USAGE);
  2447. case 'w':
  2448. if(++i < argc)
  2449. opt_embed = argv[i];
  2450. break;
  2451. }
  2452. }
  2453. run:
  2454. setlocale(LC_CTYPE, "");
  2455. tnew(80, 24);
  2456. ttynew();
  2457. xinit();
  2458. selinit();
  2459. run();
  2460. return 0;
  2461. }