st.c 53 KB

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