st.c 53 KB

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