st.c 55 KB

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