st.c 55 KB

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