st.c 60 KB

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