st.c 54 KB

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