st.c 54 KB

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