st.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909
  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 <pwd.h>
  9. #include <stdarg.h>
  10. #include <stdbool.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <signal.h>
  15. #include <sys/ioctl.h>
  16. #include <sys/select.h>
  17. #include <sys/stat.h>
  18. #include <sys/time.h>
  19. #include <sys/types.h>
  20. #include <sys/wait.h>
  21. #include <time.h>
  22. #include <unistd.h>
  23. #include <X11/Xatom.h>
  24. #include <X11/Xlib.h>
  25. #include <X11/Xutil.h>
  26. #include <X11/cursorfont.h>
  27. #include <X11/keysym.h>
  28. #include <X11/extensions/Xdbe.h>
  29. #include <X11/Xft/Xft.h>
  30. #include <fontconfig/fontconfig.h>
  31. #define Glyph Glyph_
  32. #define Font Font_
  33. #if defined(__linux)
  34. #include <pty.h>
  35. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  36. #include <util.h>
  37. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  38. #include <libutil.h>
  39. #endif
  40. #define USAGE \
  41. "st " VERSION " (c) 2010-2012 st engineers\n" \
  42. "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
  43. " [-t title] [-w windowid] [-e command ...]\n"
  44. /* XEMBED messages */
  45. #define XEMBED_FOCUS_IN 4
  46. #define XEMBED_FOCUS_OUT 5
  47. /* Arbitrary sizes */
  48. #define ESC_BUF_SIZ 256
  49. #define ESC_ARG_SIZ 16
  50. #define STR_BUF_SIZ 256
  51. #define STR_ARG_SIZ 16
  52. #define DRAW_BUF_SIZ 20*1024
  53. #define UTF_SIZ 4
  54. #define XK_NO_MOD UINT_MAX
  55. #define XK_ANY_MOD 0
  56. #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
  57. /* macros */
  58. #define CLEANMASK(mask) (mask & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
  59. #define SERRNO strerror(errno)
  60. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  61. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  62. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  63. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  64. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  65. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  66. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  67. #define IS_SET(flag) (term.mode & (flag))
  68. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
  69. #define VT102ID "\033[?6c"
  70. enum glyph_attribute {
  71. ATTR_NULL = 0,
  72. ATTR_REVERSE = 1,
  73. ATTR_UNDERLINE = 2,
  74. ATTR_BOLD = 4,
  75. ATTR_GFX = 8,
  76. ATTR_ITALIC = 16,
  77. ATTR_BLINK = 32,
  78. };
  79. enum cursor_movement {
  80. CURSOR_UP,
  81. CURSOR_DOWN,
  82. CURSOR_LEFT,
  83. CURSOR_RIGHT,
  84. CURSOR_SAVE,
  85. CURSOR_LOAD
  86. };
  87. enum cursor_state {
  88. CURSOR_DEFAULT = 0,
  89. CURSOR_WRAPNEXT = 1,
  90. CURSOR_ORIGIN = 2
  91. };
  92. enum glyph_state {
  93. GLYPH_SET = 1,
  94. GLYPH_DIRTY = 2
  95. };
  96. enum term_mode {
  97. MODE_WRAP = 1,
  98. MODE_INSERT = 2,
  99. MODE_APPKEYPAD = 4,
  100. MODE_ALTSCREEN = 8,
  101. MODE_CRLF = 16,
  102. MODE_MOUSEBTN = 32,
  103. MODE_MOUSEMOTION = 64,
  104. MODE_MOUSE = 32|64,
  105. MODE_REVERSE = 128,
  106. MODE_KBDLOCK = 256,
  107. MODE_HIDE = 512
  108. };
  109. enum escape_state {
  110. ESC_START = 1,
  111. ESC_CSI = 2,
  112. ESC_STR = 4, /* DSC, OSC, PM, APC */
  113. ESC_ALTCHARSET = 8,
  114. ESC_STR_END = 16, /* a final string was encountered */
  115. ESC_TEST = 32, /* Enter in test mode */
  116. };
  117. enum window_state {
  118. WIN_VISIBLE = 1,
  119. WIN_REDRAW = 2,
  120. WIN_FOCUSED = 4
  121. };
  122. /* bit macro */
  123. #undef B0
  124. enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
  125. typedef unsigned char uchar;
  126. typedef unsigned int uint;
  127. typedef unsigned long ulong;
  128. typedef unsigned short ushort;
  129. typedef struct {
  130. char c[UTF_SIZ]; /* character code */
  131. uchar mode; /* attribute flags */
  132. ushort fg; /* foreground */
  133. ushort bg; /* background */
  134. uchar state; /* state flags */
  135. } Glyph;
  136. typedef Glyph* Line;
  137. typedef struct {
  138. Glyph attr; /* current char attributes */
  139. int x;
  140. int y;
  141. char state;
  142. } TCursor;
  143. /* CSI Escape sequence structs */
  144. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  145. typedef struct {
  146. char buf[ESC_BUF_SIZ]; /* raw string */
  147. int len; /* raw string length */
  148. char priv;
  149. int arg[ESC_ARG_SIZ];
  150. int narg; /* nb of args */
  151. char mode;
  152. } CSIEscape;
  153. /* STR Escape sequence structs */
  154. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  155. typedef struct {
  156. char type; /* ESC type ... */
  157. char buf[STR_BUF_SIZ]; /* raw string */
  158. int len; /* raw string length */
  159. char *args[STR_ARG_SIZ];
  160. int narg; /* nb of args */
  161. } STREscape;
  162. /* Internal representation of the screen */
  163. typedef struct {
  164. int row; /* nb row */
  165. int col; /* nb col */
  166. Line *line; /* screen */
  167. Line *alt; /* alternate screen */
  168. bool *dirty; /* dirtyness of lines */
  169. TCursor c; /* cursor */
  170. int top; /* top scroll limit */
  171. int bot; /* bottom scroll limit */
  172. int mode; /* terminal mode flags */
  173. int esc; /* escape state flags */
  174. bool *tabs;
  175. } Term;
  176. /* Purely graphic info */
  177. typedef struct {
  178. Display* dpy;
  179. Colormap cmap;
  180. Window win;
  181. XdbeBackBuffer buf;
  182. Atom xembed, wmdeletewin;
  183. XIM xim;
  184. XIC xic;
  185. XftDraw *xft_draw;
  186. Visual *vis;
  187. int scr;
  188. bool isfixed; /* is fixed geometry? */
  189. int fx, fy, fw, fh; /* fixed geometry */
  190. int tw, th; /* tty width and height */
  191. int w; /* window width */
  192. int h; /* window height */
  193. int ch; /* char height */
  194. int cw; /* char width */
  195. char state; /* focus, redraw, visible */
  196. } XWindow;
  197. typedef struct {
  198. KeySym k;
  199. uint mask;
  200. char s[ESC_BUF_SIZ];
  201. } Key;
  202. /* TODO: use better name for vars... */
  203. typedef struct {
  204. int mode;
  205. int bx, by;
  206. int ex, ey;
  207. struct {
  208. int x, y;
  209. } b, e;
  210. char *clip;
  211. Atom xtarget;
  212. bool alt;
  213. struct timeval tclick1;
  214. struct timeval tclick2;
  215. } Selection;
  216. typedef union {
  217. int i;
  218. unsigned int ui;
  219. float f;
  220. const void *v;
  221. } Arg;
  222. typedef struct {
  223. unsigned int mod;
  224. KeySym keysym;
  225. void (*func)(const Arg *);
  226. const Arg arg;
  227. } Shortcut;
  228. /* function definitions used in config.h */
  229. static void xzoom(const Arg *);
  230. /* Config.h for applying patches and the configuration. */
  231. #include "config.h"
  232. /* Font structure */
  233. typedef struct {
  234. int height;
  235. int width;
  236. int ascent;
  237. int descent;
  238. short lbearing;
  239. short rbearing;
  240. XftFont *xft_set;
  241. } Font;
  242. /* Drawing Context */
  243. typedef struct {
  244. XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
  245. GC gc;
  246. Font font, bfont, ifont, ibfont;
  247. } DC;
  248. static void die(const char *, ...);
  249. static void draw(void);
  250. static void redraw(void);
  251. static void drawregion(int, int, int, int);
  252. static void execsh(void);
  253. static void sigchld(int);
  254. static void run(void);
  255. static void csidump(void);
  256. static void csihandle(void);
  257. static void csiparse(void);
  258. static void csireset(void);
  259. static void strdump(void);
  260. static void strhandle(void);
  261. static void strparse(void);
  262. static void strreset(void);
  263. static void tclearregion(int, int, int, int);
  264. static void tcursor(int);
  265. static void tdeletechar(int);
  266. static void tdeleteline(int);
  267. static void tinsertblank(int);
  268. static void tinsertblankline(int);
  269. static void tmoveto(int, int);
  270. static void tmoveato(int x, int y);
  271. static void tnew(int, int);
  272. static void tnewline(int);
  273. static void tputtab(bool);
  274. static void tputc(char *, int);
  275. static void treset(void);
  276. static int tresize(int, int);
  277. static void tscrollup(int, int);
  278. static void tscrolldown(int, int);
  279. static void tsetattr(int*, int);
  280. static void tsetchar(char *, Glyph *, int, int);
  281. static void tsetscroll(int, int);
  282. static void tswapscreen(void);
  283. static void tsetdirt(int, int);
  284. static void tsetmode(bool, bool, int *, int);
  285. static void tfulldirt(void);
  286. static void ttynew(void);
  287. static void ttyread(void);
  288. static void ttyresize(void);
  289. static void ttywrite(const char *, size_t);
  290. static void xdraws(char *, Glyph, int, int, int, int);
  291. static void xhints(void);
  292. static void xclear(int, int, int, int);
  293. static void xdrawcursor(void);
  294. static void xinit(void);
  295. static void xloadcols(void);
  296. static void xresettitle(void);
  297. static void xseturgency(int);
  298. static void xsetsel(char*);
  299. static void xtermclear(int, int, int, int);
  300. static void xresize(int, int);
  301. static void expose(XEvent *);
  302. static void visibility(XEvent *);
  303. static void unmap(XEvent *);
  304. static char *kmap(KeySym, uint);
  305. static void kpress(XEvent *);
  306. static void cmessage(XEvent *);
  307. static void cresize(int width, int height);
  308. static void resize(XEvent *);
  309. static void focus(XEvent *);
  310. static void brelease(XEvent *);
  311. static void bpress(XEvent *);
  312. static void bmotion(XEvent *);
  313. static void selnotify(XEvent *);
  314. static void selclear(XEvent *);
  315. static void selrequest(XEvent *);
  316. static void selinit(void);
  317. static inline bool selected(int, int);
  318. static void selcopy(void);
  319. static void selpaste(void);
  320. static void selscroll(int, int);
  321. static int utf8decode(char *, long *);
  322. static int utf8encode(long *, char *);
  323. static int utf8size(char *);
  324. static int isfullutf8(char *, int);
  325. static ssize_t xwrite(int, char *, size_t);
  326. static void *xmalloc(size_t);
  327. static void *xrealloc(void *, size_t);
  328. static void *xcalloc(size_t nmemb, size_t size);
  329. static void (*handler[LASTEvent])(XEvent *) = {
  330. [KeyPress] = kpress,
  331. [ClientMessage] = cmessage,
  332. [ConfigureNotify] = resize,
  333. [VisibilityNotify] = visibility,
  334. [UnmapNotify] = unmap,
  335. [Expose] = expose,
  336. [FocusIn] = focus,
  337. [FocusOut] = focus,
  338. [MotionNotify] = bmotion,
  339. [ButtonPress] = bpress,
  340. [ButtonRelease] = brelease,
  341. [SelectionClear] = selclear,
  342. [SelectionNotify] = selnotify,
  343. [SelectionRequest] = selrequest,
  344. };
  345. /* Globals */
  346. static DC dc;
  347. static XWindow xw;
  348. static Term term;
  349. static CSIEscape csiescseq;
  350. static STREscape strescseq;
  351. static int cmdfd;
  352. static pid_t pid;
  353. static Selection sel;
  354. static int iofd = -1;
  355. static char **opt_cmd = NULL;
  356. static char *opt_io = NULL;
  357. static char *opt_title = NULL;
  358. static char *opt_embed = NULL;
  359. static char *opt_class = NULL;
  360. static char *opt_font = NULL;
  361. static char *usedfont = NULL;
  362. static int usedfontsize = 0;
  363. ssize_t
  364. xwrite(int fd, char *s, size_t len) {
  365. size_t aux = len;
  366. while(len > 0) {
  367. ssize_t r = write(fd, s, len);
  368. if(r < 0)
  369. return r;
  370. len -= r;
  371. s += r;
  372. }
  373. return aux;
  374. }
  375. void *
  376. xmalloc(size_t len) {
  377. void *p = malloc(len);
  378. if(!p)
  379. die("Out of memory\n");
  380. return p;
  381. }
  382. void *
  383. xrealloc(void *p, size_t len) {
  384. if((p = realloc(p, len)) == NULL)
  385. die("Out of memory\n");
  386. return p;
  387. }
  388. void *
  389. xcalloc(size_t nmemb, size_t size) {
  390. void *p = calloc(nmemb, size);
  391. if(!p)
  392. die("Out of memory\n");
  393. return p;
  394. }
  395. int
  396. utf8decode(char *s, long *u) {
  397. uchar c;
  398. int i, n, rtn;
  399. rtn = 1;
  400. c = *s;
  401. if(~c & B7) { /* 0xxxxxxx */
  402. *u = c;
  403. return rtn;
  404. } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
  405. *u = c&(B4|B3|B2|B1|B0);
  406. n = 1;
  407. } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
  408. *u = c&(B3|B2|B1|B0);
  409. n = 2;
  410. } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
  411. *u = c & (B2|B1|B0);
  412. n = 3;
  413. } else {
  414. goto invalid;
  415. }
  416. for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
  417. c = *s;
  418. if((c & (B7|B6)) != B7) /* 10xxxxxx */
  419. goto invalid;
  420. *u <<= 6;
  421. *u |= c & (B5|B4|B3|B2|B1|B0);
  422. }
  423. if((n == 1 && *u < 0x80) ||
  424. (n == 2 && *u < 0x800) ||
  425. (n == 3 && *u < 0x10000) ||
  426. (*u >= 0xD800 && *u <= 0xDFFF)) {
  427. goto invalid;
  428. }
  429. return rtn;
  430. invalid:
  431. *u = 0xFFFD;
  432. return rtn;
  433. }
  434. int
  435. utf8encode(long *u, char *s) {
  436. uchar *sp;
  437. ulong uc;
  438. int i, n;
  439. sp = (uchar *)s;
  440. uc = *u;
  441. if(uc < 0x80) {
  442. *sp = uc; /* 0xxxxxxx */
  443. return 1;
  444. } else if(*u < 0x800) {
  445. *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
  446. n = 1;
  447. } else if(uc < 0x10000) {
  448. *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
  449. n = 2;
  450. } else if(uc <= 0x10FFFF) {
  451. *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
  452. n = 3;
  453. } else {
  454. goto invalid;
  455. }
  456. for(i=n,++sp; i>0; --i,++sp)
  457. *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
  458. return n+1;
  459. invalid:
  460. /* U+FFFD */
  461. *s++ = '\xEF';
  462. *s++ = '\xBF';
  463. *s = '\xBD';
  464. return 3;
  465. }
  466. /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
  467. UTF-8 otherwise return 0 */
  468. int
  469. isfullutf8(char *s, int b) {
  470. uchar *c1, *c2, *c3;
  471. c1 = (uchar *)s;
  472. c2 = (uchar *)++s;
  473. c3 = (uchar *)++s;
  474. if(b < 1) {
  475. return 0;
  476. } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
  477. return 0;
  478. } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
  479. ((b == 1) ||
  480. ((b == 2) && (*c2&(B7|B6)) == B7))) {
  481. return 0;
  482. } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
  483. ((b == 1) ||
  484. ((b == 2) && (*c2&(B7|B6)) == B7) ||
  485. ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
  486. return 0;
  487. } else {
  488. return 1;
  489. }
  490. }
  491. int
  492. utf8size(char *s) {
  493. uchar c = *s;
  494. if(~c&B7) {
  495. return 1;
  496. } else if((c&(B7|B6|B5)) == (B7|B6)) {
  497. return 2;
  498. } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
  499. return 3;
  500. } else {
  501. return 4;
  502. }
  503. }
  504. void
  505. selinit(void) {
  506. memset(&sel.tclick1, 0, sizeof(sel.tclick1));
  507. memset(&sel.tclick2, 0, sizeof(sel.tclick2));
  508. sel.mode = 0;
  509. sel.bx = -1;
  510. sel.clip = NULL;
  511. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  512. if(sel.xtarget == None)
  513. sel.xtarget = XA_STRING;
  514. }
  515. static int
  516. x2col(int x) {
  517. x -= borderpx;
  518. x /= xw.cw;
  519. return LIMIT(x, 0, term.col-1);
  520. }
  521. static int
  522. y2row(int y) {
  523. y -= borderpx;
  524. y /= xw.ch;
  525. return LIMIT(y, 0, term.row-1);
  526. }
  527. static inline bool
  528. selected(int x, int y) {
  529. int bx, ex;
  530. if(sel.ey == y && sel.by == y) {
  531. bx = MIN(sel.bx, sel.ex);
  532. ex = MAX(sel.bx, sel.ex);
  533. return BETWEEN(x, bx, ex);
  534. }
  535. return ((sel.b.y < y && y < sel.e.y)
  536. || (y == sel.e.y && x <= sel.e.x))
  537. || (y == sel.b.y && x >= sel.b.x
  538. && (x <= sel.e.x || sel.b.y != sel.e.y));
  539. }
  540. void
  541. getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
  542. if(b)
  543. *b = e->xbutton.button;
  544. *x = x2col(e->xbutton.x);
  545. *y = y2row(e->xbutton.y);
  546. sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
  547. sel.b.y = MIN(sel.by, sel.ey);
  548. sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
  549. sel.e.y = MAX(sel.by, sel.ey);
  550. }
  551. void
  552. mousereport(XEvent *e) {
  553. int x = x2col(e->xbutton.x);
  554. int y = y2row(e->xbutton.y);
  555. int button = e->xbutton.button;
  556. int state = e->xbutton.state;
  557. char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
  558. static int ob, ox, oy;
  559. /* from urxvt */
  560. if(e->xbutton.type == MotionNotify) {
  561. if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
  562. return;
  563. button = ob + 32;
  564. ox = x, oy = y;
  565. } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
  566. button = 3;
  567. } else {
  568. button -= Button1;
  569. if(button >= 3)
  570. button += 64 - 3;
  571. if(e->xbutton.type == ButtonPress) {
  572. ob = button;
  573. ox = x, oy = y;
  574. }
  575. }
  576. buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
  577. + (state & Mod4Mask ? 8 : 0)
  578. + (state & ControlMask ? 16 : 0);
  579. ttywrite(buf, sizeof(buf));
  580. }
  581. void
  582. bpress(XEvent *e) {
  583. if(IS_SET(MODE_MOUSE)) {
  584. mousereport(e);
  585. } else if(e->xbutton.button == Button1) {
  586. if(sel.bx != -1) {
  587. sel.bx = -1;
  588. tsetdirt(sel.b.y, sel.e.y);
  589. draw();
  590. }
  591. sel.mode = 1;
  592. sel.ex = sel.bx = x2col(e->xbutton.x);
  593. sel.ey = sel.by = y2row(e->xbutton.y);
  594. } else if(e->xbutton.button == Button4) {
  595. ttywrite("\031", 1);
  596. } else if(e->xbutton.button == Button5) {
  597. ttywrite("\005", 1);
  598. }
  599. }
  600. void
  601. selcopy(void) {
  602. char *str, *ptr, *p;
  603. int x, y, bufsize, is_selected = 0, size;
  604. Glyph *gp, *last;
  605. if(sel.bx == -1) {
  606. str = NULL;
  607. } else {
  608. bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
  609. ptr = str = xmalloc(bufsize);
  610. /* append every set & selected glyph to the selection */
  611. for(y = 0; y < term.row; y++) {
  612. gp = &term.line[y][0];
  613. last = gp + term.col;
  614. while(--last >= gp && !(last->state & GLYPH_SET))
  615. /* nothing */;
  616. for(x = 0; gp <= last; x++, ++gp) {
  617. if(!(is_selected = selected(x, y)))
  618. continue;
  619. p = (gp->state & GLYPH_SET) ? gp->c : " ";
  620. size = utf8size(p);
  621. memcpy(ptr, p, size);
  622. ptr += size;
  623. }
  624. /* \n at the end of every selected line except for the last one */
  625. if(is_selected && y < sel.e.y)
  626. *ptr++ = '\n';
  627. }
  628. *ptr = 0;
  629. }
  630. sel.alt = IS_SET(MODE_ALTSCREEN);
  631. xsetsel(str);
  632. }
  633. void
  634. selnotify(XEvent *e) {
  635. ulong nitems, ofs, rem;
  636. int format;
  637. uchar *data;
  638. Atom type;
  639. ofs = 0;
  640. do {
  641. if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
  642. False, AnyPropertyType, &type, &format,
  643. &nitems, &rem, &data)) {
  644. fprintf(stderr, "Clipboard allocation failed\n");
  645. return;
  646. }
  647. ttywrite((const char *) data, nitems * format / 8);
  648. XFree(data);
  649. /* number of 32-bit chunks returned */
  650. ofs += nitems * format / 32;
  651. } while(rem > 0);
  652. }
  653. void
  654. selpaste(void) {
  655. XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
  656. xw.win, CurrentTime);
  657. }
  658. void selclear(XEvent *e) {
  659. if(sel.bx == -1)
  660. return;
  661. sel.bx = -1;
  662. tsetdirt(sel.b.y, sel.e.y);
  663. }
  664. void
  665. selrequest(XEvent *e) {
  666. XSelectionRequestEvent *xsre;
  667. XSelectionEvent xev;
  668. Atom xa_targets, string;
  669. xsre = (XSelectionRequestEvent *) e;
  670. xev.type = SelectionNotify;
  671. xev.requestor = xsre->requestor;
  672. xev.selection = xsre->selection;
  673. xev.target = xsre->target;
  674. xev.time = xsre->time;
  675. /* reject */
  676. xev.property = None;
  677. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  678. if(xsre->target == xa_targets) {
  679. /* respond with the supported type */
  680. string = sel.xtarget;
  681. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  682. XA_ATOM, 32, PropModeReplace,
  683. (uchar *) &string, 1);
  684. xev.property = xsre->property;
  685. } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
  686. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  687. xsre->target, 8, PropModeReplace,
  688. (uchar *) sel.clip, strlen(sel.clip));
  689. xev.property = xsre->property;
  690. }
  691. /* all done, send a notification to the listener */
  692. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  693. fprintf(stderr, "Error sending SelectionNotify event\n");
  694. }
  695. void
  696. xsetsel(char *str) {
  697. /* register the selection for both the clipboard and the primary */
  698. Atom clipboard;
  699. free(sel.clip);
  700. sel.clip = str;
  701. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
  702. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  703. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  704. }
  705. void
  706. brelease(XEvent *e) {
  707. struct timeval now;
  708. if(IS_SET(MODE_MOUSE)) {
  709. mousereport(e);
  710. return;
  711. }
  712. if(e->xbutton.button == Button2) {
  713. selpaste();
  714. } else if(e->xbutton.button == Button1) {
  715. sel.mode = 0;
  716. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  717. term.dirty[sel.ey] = 1;
  718. if(sel.bx == sel.ex && sel.by == sel.ey) {
  719. sel.bx = -1;
  720. gettimeofday(&now, NULL);
  721. if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
  722. /* triple click on the line */
  723. sel.b.x = sel.bx = 0;
  724. sel.e.x = sel.ex = term.col;
  725. sel.b.y = sel.e.y = sel.ey;
  726. selcopy();
  727. } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
  728. /* double click to select word */
  729. sel.bx = sel.ex;
  730. while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
  731. term.line[sel.ey][sel.bx-1].c[0] != ' ') {
  732. sel.bx--;
  733. }
  734. sel.b.x = sel.bx;
  735. while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
  736. term.line[sel.ey][sel.ex+1].c[0] != ' ') {
  737. sel.ex++;
  738. }
  739. sel.e.x = sel.ex;
  740. sel.b.y = sel.e.y = sel.ey;
  741. selcopy();
  742. }
  743. } else {
  744. selcopy();
  745. }
  746. }
  747. memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
  748. gettimeofday(&sel.tclick1, NULL);
  749. }
  750. void
  751. bmotion(XEvent *e) {
  752. int starty, endy, oldey, oldex;
  753. if(IS_SET(MODE_MOUSE)) {
  754. mousereport(e);
  755. return;
  756. }
  757. if(sel.mode) {
  758. oldey = sel.ey;
  759. oldex = sel.ex;
  760. getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
  761. if(oldey != sel.ey || oldex != sel.ex) {
  762. starty = MIN(oldey, sel.ey);
  763. endy = MAX(oldey, sel.ey);
  764. tsetdirt(starty, endy);
  765. }
  766. }
  767. }
  768. void
  769. die(const char *errstr, ...) {
  770. va_list ap;
  771. va_start(ap, errstr);
  772. vfprintf(stderr, errstr, ap);
  773. va_end(ap);
  774. exit(EXIT_FAILURE);
  775. }
  776. void
  777. execsh(void) {
  778. char **args;
  779. char *envshell = getenv("SHELL");
  780. const struct passwd *pass = getpwuid(getuid());
  781. char buf[sizeof(long) * 8 + 1];
  782. unsetenv("COLUMNS");
  783. unsetenv("LINES");
  784. unsetenv("TERMCAP");
  785. if(pass) {
  786. setenv("LOGNAME", pass->pw_name, 1);
  787. setenv("USER", pass->pw_name, 1);
  788. setenv("SHELL", pass->pw_shell, 0);
  789. setenv("HOME", pass->pw_dir, 0);
  790. }
  791. snprintf(buf, sizeof(buf), "%lu", xw.win);
  792. setenv("WINDOWID", buf, 1);
  793. signal(SIGCHLD, SIG_DFL);
  794. signal(SIGHUP, SIG_DFL);
  795. signal(SIGINT, SIG_DFL);
  796. signal(SIGQUIT, SIG_DFL);
  797. signal(SIGTERM, SIG_DFL);
  798. signal(SIGALRM, SIG_DFL);
  799. DEFAULT(envshell, shell);
  800. setenv("TERM", termname, 1);
  801. args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
  802. execvp(args[0], args);
  803. exit(EXIT_FAILURE);
  804. }
  805. void
  806. sigchld(int a) {
  807. int stat = 0;
  808. if(waitpid(pid, &stat, 0) < 0)
  809. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  810. if(WIFEXITED(stat)) {
  811. exit(WEXITSTATUS(stat));
  812. } else {
  813. exit(EXIT_FAILURE);
  814. }
  815. }
  816. void
  817. ttynew(void) {
  818. int m, s;
  819. struct winsize w = {term.row, term.col, 0, 0};
  820. /* seems to work fine on linux, openbsd and freebsd */
  821. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  822. die("openpty failed: %s\n", SERRNO);
  823. switch(pid = fork()) {
  824. case -1:
  825. die("fork failed\n");
  826. break;
  827. case 0:
  828. setsid(); /* create a new process group */
  829. dup2(s, STDIN_FILENO);
  830. dup2(s, STDOUT_FILENO);
  831. dup2(s, STDERR_FILENO);
  832. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  833. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  834. close(s);
  835. close(m);
  836. execsh();
  837. break;
  838. default:
  839. close(s);
  840. cmdfd = m;
  841. signal(SIGCHLD, sigchld);
  842. if(opt_io) {
  843. iofd = (!strcmp(opt_io, "-")) ?
  844. STDOUT_FILENO :
  845. open(opt_io, O_WRONLY | O_CREAT, 0666);
  846. if(iofd < 0) {
  847. fprintf(stderr, "Error opening %s:%s\n",
  848. opt_io, strerror(errno));
  849. }
  850. }
  851. }
  852. }
  853. void
  854. dump(char c) {
  855. static int col;
  856. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  857. if(++col % 10 == 0)
  858. fprintf(stderr, "\n");
  859. }
  860. void
  861. ttyread(void) {
  862. static char buf[BUFSIZ];
  863. static int buflen = 0;
  864. char *ptr;
  865. char s[UTF_SIZ];
  866. int charsize; /* size of utf8 char in bytes */
  867. long utf8c;
  868. int ret;
  869. /* append read bytes to unprocessed bytes */
  870. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  871. die("Couldn't read from shell: %s\n", SERRNO);
  872. /* process every complete utf8 char */
  873. buflen += ret;
  874. ptr = buf;
  875. while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
  876. charsize = utf8decode(ptr, &utf8c);
  877. utf8encode(&utf8c, s);
  878. tputc(s, charsize);
  879. ptr += charsize;
  880. buflen -= charsize;
  881. }
  882. /* keep any uncomplete utf8 char for the next call */
  883. memmove(buf, ptr, buflen);
  884. }
  885. void
  886. ttywrite(const char *s, size_t n) {
  887. if(write(cmdfd, s, n) == -1)
  888. die("write error on tty: %s\n", SERRNO);
  889. }
  890. void
  891. ttyresize(void) {
  892. struct winsize w;
  893. w.ws_row = term.row;
  894. w.ws_col = term.col;
  895. w.ws_xpixel = xw.tw;
  896. w.ws_ypixel = xw.th;
  897. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  898. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  899. }
  900. void
  901. tsetdirt(int top, int bot) {
  902. int i;
  903. LIMIT(top, 0, term.row-1);
  904. LIMIT(bot, 0, term.row-1);
  905. for(i = top; i <= bot; i++)
  906. term.dirty[i] = 1;
  907. }
  908. void
  909. tfulldirt(void) {
  910. tsetdirt(0, term.row-1);
  911. }
  912. void
  913. tcursor(int mode) {
  914. static TCursor c;
  915. if(mode == CURSOR_SAVE) {
  916. c = term.c;
  917. } else if(mode == CURSOR_LOAD) {
  918. term.c = c;
  919. tmoveto(c.x, c.y);
  920. }
  921. }
  922. void
  923. treset(void) {
  924. uint i;
  925. term.c = (TCursor){{
  926. .mode = ATTR_NULL,
  927. .fg = defaultfg,
  928. .bg = defaultbg
  929. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  930. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  931. for(i = tabspaces; i < term.col; i += tabspaces)
  932. term.tabs[i] = 1;
  933. term.top = 0;
  934. term.bot = term.row - 1;
  935. term.mode = MODE_WRAP;
  936. tclearregion(0, 0, term.col-1, term.row-1);
  937. tmoveto(0, 0);
  938. tcursor(CURSOR_SAVE);
  939. }
  940. void
  941. tnew(int col, int row) {
  942. /* set screen size */
  943. term.row = row;
  944. term.col = col;
  945. term.line = xmalloc(term.row * sizeof(Line));
  946. term.alt = xmalloc(term.row * sizeof(Line));
  947. term.dirty = xmalloc(term.row * sizeof(*term.dirty));
  948. term.tabs = xmalloc(term.col * sizeof(*term.tabs));
  949. for(row = 0; row < term.row; row++) {
  950. term.line[row] = xmalloc(term.col * sizeof(Glyph));
  951. term.alt [row] = xmalloc(term.col * sizeof(Glyph));
  952. term.dirty[row] = 0;
  953. }
  954. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  955. /* setup screen */
  956. treset();
  957. }
  958. void
  959. tswapscreen(void) {
  960. Line *tmp = term.line;
  961. term.line = term.alt;
  962. term.alt = tmp;
  963. term.mode ^= MODE_ALTSCREEN;
  964. tfulldirt();
  965. }
  966. void
  967. tscrolldown(int orig, int n) {
  968. int i;
  969. Line temp;
  970. LIMIT(n, 0, term.bot-orig+1);
  971. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  972. for(i = term.bot; i >= orig+n; i--) {
  973. temp = term.line[i];
  974. term.line[i] = term.line[i-n];
  975. term.line[i-n] = temp;
  976. term.dirty[i] = 1;
  977. term.dirty[i-n] = 1;
  978. }
  979. selscroll(orig, n);
  980. }
  981. void
  982. tscrollup(int orig, int n) {
  983. int i;
  984. Line temp;
  985. LIMIT(n, 0, term.bot-orig+1);
  986. tclearregion(0, orig, term.col-1, orig+n-1);
  987. for(i = orig; i <= term.bot-n; i++) {
  988. temp = term.line[i];
  989. term.line[i] = term.line[i+n];
  990. term.line[i+n] = temp;
  991. term.dirty[i] = 1;
  992. term.dirty[i+n] = 1;
  993. }
  994. selscroll(orig, -n);
  995. }
  996. void
  997. selscroll(int orig, int n) {
  998. if(sel.bx == -1)
  999. return;
  1000. if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
  1001. if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
  1002. sel.bx = -1;
  1003. return;
  1004. }
  1005. if(sel.by < term.top) {
  1006. sel.by = term.top;
  1007. sel.bx = 0;
  1008. }
  1009. if(sel.ey > term.bot) {
  1010. sel.ey = term.bot;
  1011. sel.ex = term.col;
  1012. }
  1013. sel.b.y = sel.by, sel.b.x = sel.bx;
  1014. sel.e.y = sel.ey, sel.e.x = sel.ex;
  1015. }
  1016. }
  1017. void
  1018. tnewline(int first_col) {
  1019. int y = term.c.y;
  1020. if(y == term.bot) {
  1021. tscrollup(term.top, 1);
  1022. } else {
  1023. y++;
  1024. }
  1025. tmoveto(first_col ? 0 : term.c.x, y);
  1026. }
  1027. void
  1028. csiparse(void) {
  1029. /* int noarg = 1; */
  1030. char *p = csiescseq.buf;
  1031. csiescseq.narg = 0;
  1032. if(*p == '?')
  1033. csiescseq.priv = 1, p++;
  1034. while(p < csiescseq.buf+csiescseq.len) {
  1035. while(isdigit(*p)) {
  1036. csiescseq.arg[csiescseq.narg] *= 10;
  1037. csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
  1038. }
  1039. if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
  1040. csiescseq.narg++, p++;
  1041. } else {
  1042. csiescseq.mode = *p;
  1043. csiescseq.narg++;
  1044. return;
  1045. }
  1046. }
  1047. }
  1048. /* for absolute user moves, when decom is set */
  1049. void
  1050. tmoveato(int x, int y) {
  1051. tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
  1052. }
  1053. void
  1054. tmoveto(int x, int y) {
  1055. int miny, maxy;
  1056. if(term.c.state & CURSOR_ORIGIN) {
  1057. miny = term.top;
  1058. maxy = term.bot;
  1059. } else {
  1060. miny = 0;
  1061. maxy = term.row - 1;
  1062. }
  1063. LIMIT(x, 0, term.col-1);
  1064. LIMIT(y, miny, maxy);
  1065. term.c.state &= ~CURSOR_WRAPNEXT;
  1066. term.c.x = x;
  1067. term.c.y = y;
  1068. }
  1069. void
  1070. tsetchar(char *c, Glyph *attr, int x, int y) {
  1071. static char *vt100_0[62] = { /* 0x41 - 0x7e */
  1072. "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
  1073. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  1074. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  1075. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  1076. "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
  1077. "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
  1078. "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
  1079. "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
  1080. };
  1081. /*
  1082. * The table is proudly stolen from rxvt.
  1083. */
  1084. if(attr->mode & ATTR_GFX) {
  1085. if(c[0] >= 0x41 && c[0] <= 0x7e
  1086. && vt100_0[c[0] - 0x41]) {
  1087. c = vt100_0[c[0] - 0x41];
  1088. }
  1089. }
  1090. term.dirty[y] = 1;
  1091. term.line[y][x] = *attr;
  1092. memcpy(term.line[y][x].c, c, UTF_SIZ);
  1093. term.line[y][x].state |= GLYPH_SET;
  1094. }
  1095. void
  1096. tclearregion(int x1, int y1, int x2, int y2) {
  1097. int x, y, temp;
  1098. if(x1 > x2)
  1099. temp = x1, x1 = x2, x2 = temp;
  1100. if(y1 > y2)
  1101. temp = y1, y1 = y2, y2 = temp;
  1102. LIMIT(x1, 0, term.col-1);
  1103. LIMIT(x2, 0, term.col-1);
  1104. LIMIT(y1, 0, term.row-1);
  1105. LIMIT(y2, 0, term.row-1);
  1106. for(y = y1; y <= y2; y++) {
  1107. term.dirty[y] = 1;
  1108. for(x = x1; x <= x2; x++)
  1109. term.line[y][x].state = 0;
  1110. }
  1111. }
  1112. void
  1113. tdeletechar(int n) {
  1114. int src = term.c.x + n;
  1115. int dst = term.c.x;
  1116. int size = term.col - src;
  1117. term.dirty[term.c.y] = 1;
  1118. if(src >= term.col) {
  1119. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1120. return;
  1121. }
  1122. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
  1123. size * sizeof(Glyph));
  1124. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1125. }
  1126. void
  1127. tinsertblank(int n) {
  1128. int src = term.c.x;
  1129. int dst = src + n;
  1130. int size = term.col - dst;
  1131. term.dirty[term.c.y] = 1;
  1132. if(dst >= term.col) {
  1133. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1134. return;
  1135. }
  1136. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
  1137. size * sizeof(Glyph));
  1138. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1139. }
  1140. void
  1141. tinsertblankline(int n) {
  1142. if(term.c.y < term.top || term.c.y > term.bot)
  1143. return;
  1144. tscrolldown(term.c.y, n);
  1145. }
  1146. void
  1147. tdeleteline(int n) {
  1148. if(term.c.y < term.top || term.c.y > term.bot)
  1149. return;
  1150. tscrollup(term.c.y, n);
  1151. }
  1152. void
  1153. tsetattr(int *attr, int l) {
  1154. int i;
  1155. for(i = 0; i < l; i++) {
  1156. switch(attr[i]) {
  1157. case 0:
  1158. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
  1159. | ATTR_ITALIC | ATTR_BLINK);
  1160. term.c.attr.fg = defaultfg;
  1161. term.c.attr.bg = defaultbg;
  1162. break;
  1163. case 1:
  1164. term.c.attr.mode |= ATTR_BOLD;
  1165. break;
  1166. case 3: /* enter standout (highlight) */
  1167. term.c.attr.mode |= ATTR_ITALIC;
  1168. break;
  1169. case 4:
  1170. term.c.attr.mode |= ATTR_UNDERLINE;
  1171. break;
  1172. case 5:
  1173. term.c.attr.mode |= ATTR_BLINK;
  1174. break;
  1175. case 7:
  1176. term.c.attr.mode |= ATTR_REVERSE;
  1177. break;
  1178. case 21:
  1179. case 22:
  1180. term.c.attr.mode &= ~ATTR_BOLD;
  1181. break;
  1182. case 23: /* leave standout (highlight) mode */
  1183. term.c.attr.mode &= ~ATTR_ITALIC;
  1184. break;
  1185. case 24:
  1186. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1187. break;
  1188. case 25:
  1189. term.c.attr.mode &= ~ATTR_BLINK;
  1190. break;
  1191. case 27:
  1192. term.c.attr.mode &= ~ATTR_REVERSE;
  1193. break;
  1194. case 38:
  1195. if(i + 2 < l && attr[i + 1] == 5) {
  1196. i += 2;
  1197. if(BETWEEN(attr[i], 0, 255)) {
  1198. term.c.attr.fg = attr[i];
  1199. } else {
  1200. fprintf(stderr,
  1201. "erresc: bad fgcolor %d\n",
  1202. attr[i]);
  1203. }
  1204. } else {
  1205. fprintf(stderr,
  1206. "erresc(38): gfx attr %d unknown\n",
  1207. attr[i]);
  1208. }
  1209. break;
  1210. case 39:
  1211. term.c.attr.fg = defaultfg;
  1212. break;
  1213. case 48:
  1214. if(i + 2 < l && attr[i + 1] == 5) {
  1215. i += 2;
  1216. if(BETWEEN(attr[i], 0, 255)) {
  1217. term.c.attr.bg = attr[i];
  1218. } else {
  1219. fprintf(stderr,
  1220. "erresc: bad bgcolor %d\n",
  1221. attr[i]);
  1222. }
  1223. } else {
  1224. fprintf(stderr,
  1225. "erresc(48): gfx attr %d unknown\n",
  1226. attr[i]);
  1227. }
  1228. break;
  1229. case 49:
  1230. term.c.attr.bg = defaultbg;
  1231. break;
  1232. default:
  1233. if(BETWEEN(attr[i], 30, 37)) {
  1234. term.c.attr.fg = attr[i] - 30;
  1235. } else if(BETWEEN(attr[i], 40, 47)) {
  1236. term.c.attr.bg = attr[i] - 40;
  1237. } else if(BETWEEN(attr[i], 90, 97)) {
  1238. term.c.attr.fg = attr[i] - 90 + 8;
  1239. } else if(BETWEEN(attr[i], 100, 107)) {
  1240. term.c.attr.bg = attr[i] - 100 + 8;
  1241. } else {
  1242. fprintf(stderr,
  1243. "erresc(default): gfx attr %d unknown\n",
  1244. attr[i]), csidump();
  1245. }
  1246. break;
  1247. }
  1248. }
  1249. }
  1250. void
  1251. tsetscroll(int t, int b) {
  1252. int temp;
  1253. LIMIT(t, 0, term.row-1);
  1254. LIMIT(b, 0, term.row-1);
  1255. if(t > b) {
  1256. temp = t;
  1257. t = b;
  1258. b = temp;
  1259. }
  1260. term.top = t;
  1261. term.bot = b;
  1262. }
  1263. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1264. void
  1265. tsetmode(bool priv, bool set, int *args, int narg) {
  1266. int *lim, mode;
  1267. bool alt;
  1268. for(lim = args + narg; args < lim; ++args) {
  1269. if(priv) {
  1270. switch(*args) {
  1271. break;
  1272. case 1: /* DECCKM -- Cursor key */
  1273. MODBIT(term.mode, set, MODE_APPKEYPAD);
  1274. break;
  1275. case 5: /* DECSCNM -- Reverse video */
  1276. mode = term.mode;
  1277. MODBIT(term.mode, set, MODE_REVERSE);
  1278. if(mode != term.mode)
  1279. redraw();
  1280. break;
  1281. case 6: /* DECOM -- Origin */
  1282. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1283. tmoveato(0, 0);
  1284. break;
  1285. case 7: /* DECAWM -- Auto wrap */
  1286. MODBIT(term.mode, set, MODE_WRAP);
  1287. break;
  1288. case 0: /* Error (IGNORED) */
  1289. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1290. case 3: /* DECCOLM -- Column (IGNORED) */
  1291. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1292. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1293. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1294. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1295. case 42: /* DECNRCM -- National characters (IGNORED) */
  1296. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1297. break;
  1298. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1299. MODBIT(term.mode, !set, MODE_HIDE);
  1300. break;
  1301. case 1000: /* 1000,1002: enable xterm mouse report */
  1302. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1303. break;
  1304. case 1002:
  1305. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1306. break;
  1307. case 1049: /* = 1047 and 1048 */
  1308. case 47:
  1309. case 1047: {
  1310. alt = IS_SET(MODE_ALTSCREEN) != 0;
  1311. if(alt)
  1312. tclearregion(0, 0, term.col-1, term.row-1);
  1313. if(set ^ alt) /* set is always 1 or 0 */
  1314. tswapscreen();
  1315. if(*args != 1049)
  1316. break;
  1317. }
  1318. /* pass through */
  1319. case 1048:
  1320. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1321. break;
  1322. default:
  1323. fprintf(stderr,
  1324. "erresc: unknown private set/reset mode %d\n",
  1325. *args);
  1326. break;
  1327. }
  1328. } else {
  1329. switch(*args) {
  1330. case 0: /* Error (IGNORED) */
  1331. break;
  1332. case 2: /* KAM -- keyboard action */
  1333. MODBIT(term.mode, set, MODE_KBDLOCK);
  1334. break;
  1335. case 4: /* IRM -- Insertion-replacement */
  1336. MODBIT(term.mode, set, MODE_INSERT);
  1337. break;
  1338. case 12: /* XXX: SRM -- Send/Receive */
  1339. break;
  1340. case 20: /* LNM -- Linefeed/new line */
  1341. MODBIT(term.mode, set, MODE_CRLF);
  1342. break;
  1343. default:
  1344. fprintf(stderr,
  1345. "erresc: unknown set/reset mode %d\n",
  1346. *args);
  1347. break;
  1348. }
  1349. }
  1350. }
  1351. }
  1352. #undef MODBIT
  1353. void
  1354. csihandle(void) {
  1355. switch(csiescseq.mode) {
  1356. default:
  1357. unknown:
  1358. fprintf(stderr, "erresc: unknown csi ");
  1359. csidump();
  1360. /* die(""); */
  1361. break;
  1362. case '@': /* ICH -- Insert <n> blank char */
  1363. DEFAULT(csiescseq.arg[0], 1);
  1364. tinsertblank(csiescseq.arg[0]);
  1365. break;
  1366. case 'A': /* CUU -- Cursor <n> Up */
  1367. DEFAULT(csiescseq.arg[0], 1);
  1368. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1369. break;
  1370. case 'B': /* CUD -- Cursor <n> Down */
  1371. case 'e': /* VPR --Cursor <n> Down */
  1372. DEFAULT(csiescseq.arg[0], 1);
  1373. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1374. break;
  1375. case 'c': /* DA -- Device Attributes */
  1376. if(csiescseq.arg[0] == 0)
  1377. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1378. break;
  1379. case 'C': /* CUF -- Cursor <n> Forward */
  1380. case 'a': /* HPR -- Cursor <n> Forward */
  1381. DEFAULT(csiescseq.arg[0], 1);
  1382. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1383. break;
  1384. case 'D': /* CUB -- Cursor <n> Backward */
  1385. DEFAULT(csiescseq.arg[0], 1);
  1386. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1387. break;
  1388. case 'E': /* CNL -- Cursor <n> Down and first col */
  1389. DEFAULT(csiescseq.arg[0], 1);
  1390. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1391. break;
  1392. case 'F': /* CPL -- Cursor <n> Up and first col */
  1393. DEFAULT(csiescseq.arg[0], 1);
  1394. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1395. break;
  1396. case 'g': /* TBC -- Tabulation clear */
  1397. switch (csiescseq.arg[0]) {
  1398. case 0: /* clear current tab stop */
  1399. term.tabs[term.c.x] = 0;
  1400. break;
  1401. case 3: /* clear all the tabs */
  1402. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1403. break;
  1404. default:
  1405. goto unknown;
  1406. }
  1407. break;
  1408. case 'G': /* CHA -- Move to <col> */
  1409. case '`': /* HPA */
  1410. DEFAULT(csiescseq.arg[0], 1);
  1411. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1412. break;
  1413. case 'H': /* CUP -- Move to <row> <col> */
  1414. case 'f': /* HVP */
  1415. DEFAULT(csiescseq.arg[0], 1);
  1416. DEFAULT(csiescseq.arg[1], 1);
  1417. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1418. break;
  1419. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1420. DEFAULT(csiescseq.arg[0], 1);
  1421. while(csiescseq.arg[0]--)
  1422. tputtab(1);
  1423. break;
  1424. case 'J': /* ED -- Clear screen */
  1425. sel.bx = -1;
  1426. switch(csiescseq.arg[0]) {
  1427. case 0: /* below */
  1428. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1429. if(term.c.y < term.row-1)
  1430. tclearregion(0, term.c.y+1, term.col-1, term.row-1);
  1431. break;
  1432. case 1: /* above */
  1433. if(term.c.y > 1)
  1434. tclearregion(0, 0, term.col-1, term.c.y-1);
  1435. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1436. break;
  1437. case 2: /* all */
  1438. tclearregion(0, 0, term.col-1, term.row-1);
  1439. break;
  1440. default:
  1441. goto unknown;
  1442. }
  1443. break;
  1444. case 'K': /* EL -- Clear line */
  1445. switch(csiescseq.arg[0]) {
  1446. case 0: /* right */
  1447. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1448. break;
  1449. case 1: /* left */
  1450. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1451. break;
  1452. case 2: /* all */
  1453. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1454. break;
  1455. }
  1456. break;
  1457. case 'S': /* SU -- Scroll <n> line up */
  1458. DEFAULT(csiescseq.arg[0], 1);
  1459. tscrollup(term.top, csiescseq.arg[0]);
  1460. break;
  1461. case 'T': /* SD -- Scroll <n> line down */
  1462. DEFAULT(csiescseq.arg[0], 1);
  1463. tscrolldown(term.top, csiescseq.arg[0]);
  1464. break;
  1465. case 'L': /* IL -- Insert <n> blank lines */
  1466. DEFAULT(csiescseq.arg[0], 1);
  1467. tinsertblankline(csiescseq.arg[0]);
  1468. break;
  1469. case 'l': /* RM -- Reset Mode */
  1470. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1471. break;
  1472. case 'M': /* DL -- Delete <n> lines */
  1473. DEFAULT(csiescseq.arg[0], 1);
  1474. tdeleteline(csiescseq.arg[0]);
  1475. break;
  1476. case 'X': /* ECH -- Erase <n> char */
  1477. DEFAULT(csiescseq.arg[0], 1);
  1478. tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
  1479. break;
  1480. case 'P': /* DCH -- Delete <n> char */
  1481. DEFAULT(csiescseq.arg[0], 1);
  1482. tdeletechar(csiescseq.arg[0]);
  1483. break;
  1484. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1485. DEFAULT(csiescseq.arg[0], 1);
  1486. while(csiescseq.arg[0]--)
  1487. tputtab(0);
  1488. break;
  1489. case 'd': /* VPA -- Move to <row> */
  1490. DEFAULT(csiescseq.arg[0], 1);
  1491. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1492. break;
  1493. case 'h': /* SM -- Set terminal mode */
  1494. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1495. break;
  1496. case 'm': /* SGR -- Terminal attribute (color) */
  1497. tsetattr(csiescseq.arg, csiescseq.narg);
  1498. break;
  1499. case 'r': /* DECSTBM -- Set Scrolling Region */
  1500. if(csiescseq.priv) {
  1501. goto unknown;
  1502. } else {
  1503. DEFAULT(csiescseq.arg[0], 1);
  1504. DEFAULT(csiescseq.arg[1], term.row);
  1505. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1506. tmoveato(0, 0);
  1507. }
  1508. break;
  1509. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1510. tcursor(CURSOR_SAVE);
  1511. break;
  1512. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1513. tcursor(CURSOR_LOAD);
  1514. break;
  1515. }
  1516. }
  1517. void
  1518. csidump(void) {
  1519. int i;
  1520. uint c;
  1521. printf("ESC[");
  1522. for(i = 0; i < csiescseq.len; i++) {
  1523. c = csiescseq.buf[i] & 0xff;
  1524. if(isprint(c)) {
  1525. putchar(c);
  1526. } else if(c == '\n') {
  1527. printf("(\\n)");
  1528. } else if(c == '\r') {
  1529. printf("(\\r)");
  1530. } else if(c == 0x1b) {
  1531. printf("(\\e)");
  1532. } else {
  1533. printf("(%02x)", c);
  1534. }
  1535. }
  1536. putchar('\n');
  1537. }
  1538. void
  1539. csireset(void) {
  1540. memset(&csiescseq, 0, sizeof(csiescseq));
  1541. }
  1542. void
  1543. strhandle(void) {
  1544. char *p;
  1545. /*
  1546. * TODO: make this being useful in case of color palette change.
  1547. */
  1548. strparse();
  1549. p = strescseq.buf;
  1550. switch(strescseq.type) {
  1551. case ']': /* OSC -- Operating System Command */
  1552. switch(p[0]) {
  1553. case '0':
  1554. case '1':
  1555. case '2':
  1556. /*
  1557. * TODO: Handle special chars in string, like umlauts.
  1558. */
  1559. if(p[1] == ';') {
  1560. XStoreName(xw.dpy, xw.win, strescseq.buf+2);
  1561. }
  1562. break;
  1563. case ';':
  1564. XStoreName(xw.dpy, xw.win, strescseq.buf+1);
  1565. break;
  1566. case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
  1567. break;
  1568. default:
  1569. fprintf(stderr, "erresc: unknown str ");
  1570. strdump();
  1571. break;
  1572. }
  1573. break;
  1574. case 'k': /* old title set compatibility */
  1575. XStoreName(xw.dpy, xw.win, strescseq.buf);
  1576. break;
  1577. case 'P': /* DSC -- Device Control String */
  1578. case '_': /* APC -- Application Program Command */
  1579. case '^': /* PM -- Privacy Message */
  1580. default:
  1581. fprintf(stderr, "erresc: unknown str ");
  1582. strdump();
  1583. /* die(""); */
  1584. break;
  1585. }
  1586. }
  1587. void
  1588. strparse(void) {
  1589. /*
  1590. * TODO: Implement parsing like for CSI when required.
  1591. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1592. */
  1593. return;
  1594. }
  1595. void
  1596. strdump(void) {
  1597. int i;
  1598. uint c;
  1599. printf("ESC%c", strescseq.type);
  1600. for(i = 0; i < strescseq.len; i++) {
  1601. c = strescseq.buf[i] & 0xff;
  1602. if(isprint(c)) {
  1603. putchar(c);
  1604. } else if(c == '\n') {
  1605. printf("(\\n)");
  1606. } else if(c == '\r') {
  1607. printf("(\\r)");
  1608. } else if(c == 0x1b) {
  1609. printf("(\\e)");
  1610. } else {
  1611. printf("(%02x)", c);
  1612. }
  1613. }
  1614. printf("ESC\\\n");
  1615. }
  1616. void
  1617. strreset(void) {
  1618. memset(&strescseq, 0, sizeof(strescseq));
  1619. }
  1620. void
  1621. tputtab(bool forward) {
  1622. uint x = term.c.x;
  1623. if(forward) {
  1624. if(x == term.col)
  1625. return;
  1626. for(++x; x < term.col && !term.tabs[x]; ++x)
  1627. /* nothing */ ;
  1628. } else {
  1629. if(x == 0)
  1630. return;
  1631. for(--x; x > 0 && !term.tabs[x]; --x)
  1632. /* nothing */ ;
  1633. }
  1634. tmoveto(x, term.c.y);
  1635. }
  1636. void
  1637. tputc(char *c, int len) {
  1638. uchar ascii = *c;
  1639. bool control = ascii < '\x20' || ascii == 0177;
  1640. if(iofd != -1) {
  1641. if (xwrite(iofd, c, len) < 0) {
  1642. fprintf(stderr, "Error writting in %s:%s\n",
  1643. opt_io, strerror(errno));
  1644. close(iofd);
  1645. iofd = -1;
  1646. }
  1647. }
  1648. /*
  1649. * STR sequences must be checked before anything else
  1650. * because it can use some control codes as part of the sequence.
  1651. */
  1652. if(term.esc & ESC_STR) {
  1653. switch(ascii) {
  1654. case '\033':
  1655. term.esc = ESC_START | ESC_STR_END;
  1656. break;
  1657. case '\a': /* backwards compatibility to xterm */
  1658. term.esc = 0;
  1659. strhandle();
  1660. break;
  1661. default:
  1662. strescseq.buf[strescseq.len++] = ascii;
  1663. if(strescseq.len+1 >= STR_BUF_SIZ) {
  1664. term.esc = 0;
  1665. strhandle();
  1666. }
  1667. }
  1668. return;
  1669. }
  1670. /*
  1671. * Actions of control codes must be performed as soon they arrive
  1672. * because they can be embedded inside a control sequence, and
  1673. * they must not cause conflicts with sequences.
  1674. */
  1675. if(control) {
  1676. switch(ascii) {
  1677. case '\t': /* HT */
  1678. tputtab(1);
  1679. return;
  1680. case '\b': /* BS */
  1681. tmoveto(term.c.x-1, term.c.y);
  1682. return;
  1683. case '\r': /* CR */
  1684. tmoveto(0, term.c.y);
  1685. return;
  1686. case '\f': /* LF */
  1687. case '\v': /* VT */
  1688. case '\n': /* LF */
  1689. /* go to first col if the mode is set */
  1690. tnewline(IS_SET(MODE_CRLF));
  1691. return;
  1692. case '\a': /* BEL */
  1693. if(!(xw.state & WIN_FOCUSED))
  1694. xseturgency(1);
  1695. return;
  1696. case '\033': /* ESC */
  1697. csireset();
  1698. term.esc = ESC_START;
  1699. return;
  1700. case '\016': /* SO */
  1701. term.c.attr.mode |= ATTR_GFX;
  1702. return;
  1703. case '\017': /* SI */
  1704. term.c.attr.mode &= ~ATTR_GFX;
  1705. return;
  1706. case '\032': /* SUB */
  1707. case '\030': /* CAN */
  1708. csireset();
  1709. return;
  1710. case '\005': /* ENQ (IGNORED) */
  1711. case '\000': /* NUL (IGNORED) */
  1712. case '\021': /* XON (IGNORED) */
  1713. case '\023': /* XOFF (IGNORED) */
  1714. case 0177: /* DEL (IGNORED) */
  1715. return;
  1716. }
  1717. } else if(term.esc & ESC_START) {
  1718. if(term.esc & ESC_CSI) {
  1719. csiescseq.buf[csiescseq.len++] = ascii;
  1720. if(BETWEEN(ascii, 0x40, 0x7E)
  1721. || csiescseq.len >= ESC_BUF_SIZ) {
  1722. term.esc = 0;
  1723. csiparse(), csihandle();
  1724. }
  1725. } else if(term.esc & ESC_STR_END) {
  1726. term.esc = 0;
  1727. if(ascii == '\\')
  1728. strhandle();
  1729. } else if(term.esc & ESC_ALTCHARSET) {
  1730. switch(ascii) {
  1731. case '0': /* Line drawing set */
  1732. term.c.attr.mode |= ATTR_GFX;
  1733. break;
  1734. case 'B': /* USASCII */
  1735. term.c.attr.mode &= ~ATTR_GFX;
  1736. break;
  1737. case 'A': /* UK (IGNORED) */
  1738. case '<': /* multinational charset (IGNORED) */
  1739. case '5': /* Finnish (IGNORED) */
  1740. case 'C': /* Finnish (IGNORED) */
  1741. case 'K': /* German (IGNORED) */
  1742. break;
  1743. default:
  1744. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1745. }
  1746. term.esc = 0;
  1747. } else if(term.esc & ESC_TEST) {
  1748. if(ascii == '8') { /* DEC screen alignment test. */
  1749. char E[UTF_SIZ] = "E";
  1750. int x, y;
  1751. for(x = 0; x < term.col; ++x) {
  1752. for(y = 0; y < term.row; ++y)
  1753. tsetchar(E, &term.c.attr, x, y);
  1754. }
  1755. }
  1756. term.esc = 0;
  1757. } else {
  1758. switch(ascii) {
  1759. case '[':
  1760. term.esc |= ESC_CSI;
  1761. break;
  1762. case '#':
  1763. term.esc |= ESC_TEST;
  1764. break;
  1765. case 'P': /* DCS -- Device Control String */
  1766. case '_': /* APC -- Application Program Command */
  1767. case '^': /* PM -- Privacy Message */
  1768. case ']': /* OSC -- Operating System Command */
  1769. case 'k': /* old title set compatibility */
  1770. strreset();
  1771. strescseq.type = ascii;
  1772. term.esc |= ESC_STR;
  1773. break;
  1774. case '(': /* set primary charset G0 */
  1775. term.esc |= ESC_ALTCHARSET;
  1776. break;
  1777. case ')': /* set secondary charset G1 (IGNORED) */
  1778. case '*': /* set tertiary charset G2 (IGNORED) */
  1779. case '+': /* set quaternary charset G3 (IGNORED) */
  1780. term.esc = 0;
  1781. break;
  1782. case 'D': /* IND -- Linefeed */
  1783. if(term.c.y == term.bot) {
  1784. tscrollup(term.top, 1);
  1785. } else {
  1786. tmoveto(term.c.x, term.c.y+1);
  1787. }
  1788. term.esc = 0;
  1789. break;
  1790. case 'E': /* NEL -- Next line */
  1791. tnewline(1); /* always go to first col */
  1792. term.esc = 0;
  1793. break;
  1794. case 'H': /* HTS -- Horizontal tab stop */
  1795. term.tabs[term.c.x] = 1;
  1796. term.esc = 0;
  1797. break;
  1798. case 'M': /* RI -- Reverse index */
  1799. if(term.c.y == term.top) {
  1800. tscrolldown(term.top, 1);
  1801. } else {
  1802. tmoveto(term.c.x, term.c.y-1);
  1803. }
  1804. term.esc = 0;
  1805. break;
  1806. case 'Z': /* DECID -- Identify Terminal */
  1807. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1808. term.esc = 0;
  1809. break;
  1810. case 'c': /* RIS -- Reset to inital state */
  1811. treset();
  1812. term.esc = 0;
  1813. xresettitle();
  1814. break;
  1815. case '=': /* DECPAM -- Application keypad */
  1816. term.mode |= MODE_APPKEYPAD;
  1817. term.esc = 0;
  1818. break;
  1819. case '>': /* DECPNM -- Normal keypad */
  1820. term.mode &= ~MODE_APPKEYPAD;
  1821. term.esc = 0;
  1822. break;
  1823. case '7': /* DECSC -- Save Cursor */
  1824. tcursor(CURSOR_SAVE);
  1825. term.esc = 0;
  1826. break;
  1827. case '8': /* DECRC -- Restore Cursor */
  1828. tcursor(CURSOR_LOAD);
  1829. term.esc = 0;
  1830. break;
  1831. case '\\': /* ST -- Stop */
  1832. term.esc = 0;
  1833. break;
  1834. default:
  1835. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  1836. (uchar) ascii, isprint(ascii)? ascii:'.');
  1837. term.esc = 0;
  1838. }
  1839. }
  1840. /*
  1841. * All characters which forms part of a sequence are not
  1842. * printed
  1843. */
  1844. return;
  1845. }
  1846. /*
  1847. * Display control codes only if we are in graphic mode
  1848. */
  1849. if(control && !(term.c.attr.mode & ATTR_GFX))
  1850. return;
  1851. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  1852. sel.bx = -1;
  1853. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  1854. tnewline(1); /* always go to first col */
  1855. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  1856. if(term.c.x+1 < term.col)
  1857. tmoveto(term.c.x+1, term.c.y);
  1858. else
  1859. term.c.state |= CURSOR_WRAPNEXT;
  1860. }
  1861. int
  1862. tresize(int col, int row) {
  1863. int i, x;
  1864. int minrow = MIN(row, term.row);
  1865. int mincol = MIN(col, term.col);
  1866. int slide = term.c.y - row + 1;
  1867. bool *bp;
  1868. if(col < 1 || row < 1)
  1869. return 0;
  1870. /* free unneeded rows */
  1871. i = 0;
  1872. if(slide > 0) {
  1873. /* slide screen to keep cursor where we expect it -
  1874. * tscrollup would work here, but we can optimize to
  1875. * memmove because we're freeing the earlier lines */
  1876. for(/* i = 0 */; i < slide; i++) {
  1877. free(term.line[i]);
  1878. free(term.alt[i]);
  1879. }
  1880. memmove(term.line, term.line + slide, row * sizeof(Line));
  1881. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  1882. }
  1883. for(i += row; i < term.row; i++) {
  1884. free(term.line[i]);
  1885. free(term.alt[i]);
  1886. }
  1887. /* resize to new height */
  1888. term.line = xrealloc(term.line, row * sizeof(Line));
  1889. term.alt = xrealloc(term.alt, row * sizeof(Line));
  1890. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  1891. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  1892. /* resize each row to new width, zero-pad if needed */
  1893. for(i = 0; i < minrow; i++) {
  1894. term.dirty[i] = 1;
  1895. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  1896. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  1897. for(x = mincol; x < col; x++) {
  1898. term.line[i][x].state = 0;
  1899. term.alt[i][x].state = 0;
  1900. }
  1901. }
  1902. /* allocate any new rows */
  1903. for(/* i == minrow */; i < row; i++) {
  1904. term.dirty[i] = 1;
  1905. term.line[i] = xcalloc(col, sizeof(Glyph));
  1906. term.alt [i] = xcalloc(col, sizeof(Glyph));
  1907. }
  1908. if(col > term.col) {
  1909. bp = term.tabs + term.col;
  1910. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  1911. while(--bp > term.tabs && !*bp)
  1912. /* nothing */ ;
  1913. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  1914. *bp = 1;
  1915. }
  1916. /* update terminal size */
  1917. term.col = col;
  1918. term.row = row;
  1919. /* reset scrolling region */
  1920. tsetscroll(0, row-1);
  1921. /* make use of the LIMIT in tmoveto */
  1922. tmoveto(term.c.x, term.c.y);
  1923. return (slide > 0);
  1924. }
  1925. void
  1926. xresize(int col, int row) {
  1927. xw.tw = MAX(1, 2*borderpx + col * xw.cw);
  1928. xw.th = MAX(1, 2*borderpx + row * xw.ch);
  1929. XftDrawChange(xw.xft_draw, xw.buf);
  1930. }
  1931. void
  1932. xloadcols(void) {
  1933. int i, r, g, b;
  1934. XRenderColor xft_color = { .alpha = 0 };
  1935. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  1936. for(i = 0; i < LEN(colorname); i++) {
  1937. if(!colorname[i])
  1938. continue;
  1939. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
  1940. die("Could not allocate color '%s'\n", colorname[i]);
  1941. }
  1942. }
  1943. /* load colors [16-255] ; same colors as xterm */
  1944. for(i = 16, r = 0; r < 6; r++) {
  1945. for(g = 0; g < 6; g++) {
  1946. for(b = 0; b < 6; b++) {
  1947. xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
  1948. xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
  1949. xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
  1950. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
  1951. die("Could not allocate color %d\n", i);
  1952. }
  1953. i++;
  1954. }
  1955. }
  1956. }
  1957. for(r = 0; r < 24; r++, i++) {
  1958. xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
  1959. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
  1960. &dc.xft_col[i])) {
  1961. die("Could not allocate color %d\n", i);
  1962. }
  1963. }
  1964. }
  1965. void
  1966. xtermclear(int col1, int row1, int col2, int row2) {
  1967. XftDrawRect(xw.xft_draw,
  1968. &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  1969. borderpx + col1 * xw.cw,
  1970. borderpx + row1 * xw.ch,
  1971. (col2-col1+1) * xw.cw,
  1972. (row2-row1+1) * xw.ch);
  1973. }
  1974. /*
  1975. * Absolute coordinates.
  1976. */
  1977. void
  1978. xclear(int x1, int y1, int x2, int y2) {
  1979. XftDrawRect(xw.xft_draw,
  1980. &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  1981. x1, y1, x2-x1, y2-y1);
  1982. }
  1983. void
  1984. xhints(void) {
  1985. XClassHint class = {opt_class ? opt_class : termname, termname};
  1986. XWMHints wm = {.flags = InputHint, .input = 1};
  1987. XSizeHints *sizeh = NULL;
  1988. sizeh = XAllocSizeHints();
  1989. if(xw.isfixed == False) {
  1990. sizeh->flags = PSize | PResizeInc | PBaseSize;
  1991. sizeh->height = xw.h;
  1992. sizeh->width = xw.w;
  1993. sizeh->height_inc = xw.ch;
  1994. sizeh->width_inc = xw.cw;
  1995. sizeh->base_height = 2*borderpx;
  1996. sizeh->base_width = 2*borderpx;
  1997. } else {
  1998. sizeh->flags = PMaxSize | PMinSize;
  1999. sizeh->min_width = sizeh->max_width = xw.fw;
  2000. sizeh->min_height = sizeh->max_height = xw.fh;
  2001. }
  2002. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  2003. XFree(sizeh);
  2004. }
  2005. int
  2006. xloadfont(Font *f, FcPattern *pattern) {
  2007. FcPattern *match;
  2008. FcResult result;
  2009. match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
  2010. if(!match)
  2011. return 1;
  2012. if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
  2013. FcPatternDestroy(match);
  2014. return 1;
  2015. }
  2016. f->ascent = f->xft_set->ascent;
  2017. f->descent = f->xft_set->descent;
  2018. f->lbearing = 0;
  2019. f->rbearing = f->xft_set->max_advance_width;
  2020. f->height = f->xft_set->height;
  2021. f->width = f->lbearing + f->rbearing;
  2022. return 0;
  2023. }
  2024. void
  2025. xloadfonts(char *fontstr, int fontsize) {
  2026. FcPattern *pattern;
  2027. FcResult result;
  2028. double fontval;
  2029. if(fontstr[0] == '-') {
  2030. pattern = XftXlfdParse(fontstr, False, False);
  2031. } else {
  2032. pattern = FcNameParse((FcChar8 *)fontstr);
  2033. }
  2034. if(!pattern)
  2035. die("st: can't open font %s\n", fontstr);
  2036. if(fontsize > 0) {
  2037. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2038. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2039. usedfontsize = fontsize;
  2040. } else {
  2041. result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2042. if(result == FcResultMatch) {
  2043. usedfontsize = (int)fontval;
  2044. } else {
  2045. /*
  2046. * Default font size is 12, if none given. This is to
  2047. * have a known usedfontsize value.
  2048. */
  2049. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2050. usedfontsize = 12;
  2051. }
  2052. }
  2053. if(xloadfont(&dc.font, pattern))
  2054. die("st: can't open font %s\n", fontstr);
  2055. /* Setting character width and height. */
  2056. xw.cw = dc.font.width;
  2057. xw.ch = dc.font.height;
  2058. FcPatternDel(pattern, FC_WEIGHT);
  2059. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2060. if(xloadfont(&dc.bfont, pattern))
  2061. die("st: can't open font %s\n", fontstr);
  2062. FcPatternDel(pattern, FC_SLANT);
  2063. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2064. if(xloadfont(&dc.ibfont, pattern))
  2065. die("st: can't open font %s\n", fontstr);
  2066. FcPatternDel(pattern, FC_WEIGHT);
  2067. if(xloadfont(&dc.ifont, pattern))
  2068. die("st: can't open font %s\n", fontstr);
  2069. FcPatternDestroy(pattern);
  2070. }
  2071. void
  2072. xzoom(const Arg *arg)
  2073. {
  2074. xloadfonts(usedfont, usedfontsize + arg->i);
  2075. cresize(0, 0);
  2076. draw();
  2077. }
  2078. void
  2079. xinit(void) {
  2080. XSetWindowAttributes attrs;
  2081. Cursor cursor;
  2082. Window parent;
  2083. int sw, sh, major, minor;
  2084. if(!(xw.dpy = XOpenDisplay(NULL)))
  2085. die("Can't open display\n");
  2086. xw.scr = XDefaultScreen(xw.dpy);
  2087. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2088. /* font */
  2089. usedfont = (opt_font == NULL)? font : opt_font;
  2090. xloadfonts(usedfont, 0);
  2091. /* colors */
  2092. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2093. xloadcols();
  2094. /* adjust fixed window geometry */
  2095. if(xw.isfixed) {
  2096. sw = DisplayWidth(xw.dpy, xw.scr);
  2097. sh = DisplayHeight(xw.dpy, xw.scr);
  2098. if(xw.fx < 0)
  2099. xw.fx = sw + xw.fx - xw.fw - 1;
  2100. if(xw.fy < 0)
  2101. xw.fy = sh + xw.fy - xw.fh - 1;
  2102. xw.h = xw.fh;
  2103. xw.w = xw.fw;
  2104. } else {
  2105. /* window - default size */
  2106. xw.h = 2*borderpx + term.row * xw.ch;
  2107. xw.w = 2*borderpx + term.col * xw.cw;
  2108. xw.fx = 0;
  2109. xw.fy = 0;
  2110. }
  2111. attrs.background_pixel = dc.xft_col[defaultbg].pixel;
  2112. attrs.border_pixel = dc.xft_col[defaultbg].pixel;
  2113. attrs.bit_gravity = NorthWestGravity;
  2114. attrs.event_mask = FocusChangeMask | KeyPressMask
  2115. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2116. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2117. attrs.colormap = xw.cmap;
  2118. parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
  2119. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  2120. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2121. xw.vis,
  2122. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  2123. | CWColormap,
  2124. &attrs);
  2125. /* double buffering */
  2126. if(!XdbeQueryExtension(xw.dpy, &major, &minor))
  2127. die("Xdbe extension is not present\n");
  2128. xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
  2129. /* Xft rendering context */
  2130. xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2131. /* input methods */
  2132. xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  2133. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2134. | XIMStatusNothing, XNClientWindow, xw.win,
  2135. XNFocusWindow, xw.win, NULL);
  2136. /* gc */
  2137. dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
  2138. /* white cursor, black outline */
  2139. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2140. XDefineCursor(xw.dpy, xw.win, cursor);
  2141. XRecolorCursor(xw.dpy, cursor,
  2142. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2143. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2144. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2145. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2146. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2147. xresettitle();
  2148. XMapWindow(xw.dpy, xw.win);
  2149. xhints();
  2150. XSync(xw.dpy, 0);
  2151. }
  2152. void
  2153. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2154. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2155. width = charlen * xw.cw;
  2156. Font *font = &dc.font;
  2157. XGlyphInfo extents;
  2158. XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
  2159. *temp, revfg, revbg;
  2160. XRenderColor colfg, colbg;
  2161. if(base.mode & ATTR_BOLD) {
  2162. if(BETWEEN(base.fg, 0, 7)) {
  2163. /* basic system colors */
  2164. fg = &dc.xft_col[base.fg + 8];
  2165. } else if(BETWEEN(base.fg, 16, 195)) {
  2166. /* 256 colors */
  2167. fg = &dc.xft_col[base.fg + 36];
  2168. } else if(BETWEEN(base.fg, 232, 251)) {
  2169. /* greyscale */
  2170. fg = &dc.xft_col[base.fg + 4];
  2171. }
  2172. /*
  2173. * Those ranges will not be brightened:
  2174. * 8 - 15 – bright system colors
  2175. * 196 - 231 – highest 256 color cube
  2176. * 252 - 255 – brightest colors in greyscale
  2177. */
  2178. font = &dc.bfont;
  2179. }
  2180. if(base.mode & ATTR_ITALIC)
  2181. font = &dc.ifont;
  2182. if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
  2183. font = &dc.ibfont;
  2184. if(IS_SET(MODE_REVERSE)) {
  2185. if(fg == &dc.xft_col[defaultfg]) {
  2186. fg = &dc.xft_col[defaultbg];
  2187. } else {
  2188. colfg.red = ~fg->color.red;
  2189. colfg.green = ~fg->color.green;
  2190. colfg.blue = ~fg->color.blue;
  2191. colfg.alpha = fg->color.alpha;
  2192. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2193. fg = &revfg;
  2194. }
  2195. if(bg == &dc.xft_col[defaultbg]) {
  2196. bg = &dc.xft_col[defaultfg];
  2197. } else {
  2198. colbg.red = ~bg->color.red;
  2199. colbg.green = ~bg->color.green;
  2200. colbg.blue = ~bg->color.blue;
  2201. colbg.alpha = bg->color.alpha;
  2202. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
  2203. bg = &revbg;
  2204. }
  2205. }
  2206. if(base.mode & ATTR_REVERSE)
  2207. temp = fg, fg = bg, bg = temp;
  2208. XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
  2209. &extents);
  2210. width = extents.xOff;
  2211. /* Intelligent cleaning up of the borders. */
  2212. if(x == 0) {
  2213. xclear(0, (y == 0)? 0 : winy, borderpx,
  2214. winy + xw.ch + (y == term.row-1)? xw.h : 0);
  2215. }
  2216. if(x + charlen >= term.col-1) {
  2217. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2218. (y == term.row-1)? xw.h : (winy + xw.ch));
  2219. }
  2220. if(y == 0)
  2221. xclear(winx, 0, winx + width, borderpx);
  2222. if(y == term.row-1)
  2223. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2224. XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
  2225. XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
  2226. winy + font->ascent, (FcChar8 *)s, bytelen);
  2227. if(base.mode & ATTR_UNDERLINE) {
  2228. XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
  2229. width, 1);
  2230. }
  2231. }
  2232. void
  2233. xdrawcursor(void) {
  2234. static int oldx = 0, oldy = 0;
  2235. int sl;
  2236. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
  2237. LIMIT(oldx, 0, term.col-1);
  2238. LIMIT(oldy, 0, term.row-1);
  2239. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  2240. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  2241. /* remove the old cursor */
  2242. if(term.line[oldy][oldx].state & GLYPH_SET) {
  2243. sl = utf8size(term.line[oldy][oldx].c);
  2244. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  2245. oldy, 1, sl);
  2246. } else {
  2247. xtermclear(oldx, oldy, oldx, oldy);
  2248. }
  2249. /* draw the new one */
  2250. if(!(IS_SET(MODE_HIDE))) {
  2251. if(!(xw.state & WIN_FOCUSED))
  2252. g.bg = defaultucs;
  2253. if(IS_SET(MODE_REVERSE))
  2254. g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
  2255. sl = utf8size(g.c);
  2256. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  2257. oldx = term.c.x, oldy = term.c.y;
  2258. }
  2259. }
  2260. void
  2261. xresettitle(void) {
  2262. XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
  2263. }
  2264. void
  2265. redraw(void) {
  2266. struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
  2267. tfulldirt();
  2268. draw();
  2269. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2270. nanosleep(&tv, NULL);
  2271. }
  2272. void
  2273. draw(void) {
  2274. XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
  2275. drawregion(0, 0, term.col, term.row);
  2276. XdbeSwapBuffers(xw.dpy, swpinfo, 1);
  2277. }
  2278. void
  2279. drawregion(int x1, int y1, int x2, int y2) {
  2280. int ic, ib, x, y, ox, sl;
  2281. Glyph base, new;
  2282. char buf[DRAW_BUF_SIZ];
  2283. bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN) != 0;
  2284. if((sel.alt != 0) ^ alt)
  2285. ena_sel = 0;
  2286. if(!(xw.state & WIN_VISIBLE))
  2287. return;
  2288. for(y = y1; y < y2; y++) {
  2289. if(!term.dirty[y])
  2290. continue;
  2291. xtermclear(0, y, term.col, y);
  2292. term.dirty[y] = 0;
  2293. base = term.line[y][0];
  2294. ic = ib = ox = 0;
  2295. for(x = x1; x < x2; x++) {
  2296. new = term.line[y][x];
  2297. if(ena_sel && *(new.c) && selected(x, y))
  2298. new.mode ^= ATTR_REVERSE;
  2299. if(ib > 0 && (!(new.state & GLYPH_SET)
  2300. || ATTRCMP(base, new)
  2301. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  2302. xdraws(buf, base, ox, y, ic, ib);
  2303. ic = ib = 0;
  2304. }
  2305. if(new.state & GLYPH_SET) {
  2306. if(ib == 0) {
  2307. ox = x;
  2308. base = new;
  2309. }
  2310. sl = utf8size(new.c);
  2311. memcpy(buf+ib, new.c, sl);
  2312. ib += sl;
  2313. ++ic;
  2314. }
  2315. }
  2316. if(ib > 0)
  2317. xdraws(buf, base, ox, y, ic, ib);
  2318. }
  2319. xdrawcursor();
  2320. }
  2321. void
  2322. expose(XEvent *ev) {
  2323. XExposeEvent *e = &ev->xexpose;
  2324. if(xw.state & WIN_REDRAW) {
  2325. if(!e->count)
  2326. xw.state &= ~WIN_REDRAW;
  2327. }
  2328. }
  2329. void
  2330. visibility(XEvent *ev) {
  2331. XVisibilityEvent *e = &ev->xvisibility;
  2332. if(e->state == VisibilityFullyObscured) {
  2333. xw.state &= ~WIN_VISIBLE;
  2334. } else if(!(xw.state & WIN_VISIBLE)) {
  2335. /* need a full redraw for next Expose, not just a buf copy */
  2336. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2337. }
  2338. }
  2339. void
  2340. unmap(XEvent *ev) {
  2341. xw.state &= ~WIN_VISIBLE;
  2342. }
  2343. void
  2344. xseturgency(int add) {
  2345. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2346. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2347. XSetWMHints(xw.dpy, xw.win, h);
  2348. XFree(h);
  2349. }
  2350. void
  2351. focus(XEvent *ev) {
  2352. if(ev->type == FocusIn) {
  2353. XSetICFocus(xw.xic);
  2354. xw.state |= WIN_FOCUSED;
  2355. xseturgency(0);
  2356. } else {
  2357. XUnsetICFocus(xw.xic);
  2358. xw.state &= ~WIN_FOCUSED;
  2359. }
  2360. }
  2361. char*
  2362. kmap(KeySym k, uint state) {
  2363. int i;
  2364. uint mask;
  2365. state &= ~Mod2Mask;
  2366. for(i = 0; i < LEN(key); i++) {
  2367. mask = key[i].mask;
  2368. if(key[i].k == k && ((state & mask) == mask
  2369. || (mask == XK_NO_MOD && !state))) {
  2370. return (char*)key[i].s;
  2371. }
  2372. }
  2373. return NULL;
  2374. }
  2375. void
  2376. kpress(XEvent *ev) {
  2377. XKeyEvent *e = &ev->xkey;
  2378. KeySym ksym;
  2379. char buf[32], *customkey;
  2380. int len, meta, shift, i;
  2381. Status status;
  2382. if (IS_SET(MODE_KBDLOCK))
  2383. return;
  2384. meta = e->state & Mod1Mask;
  2385. shift = e->state & ShiftMask;
  2386. len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
  2387. /* 1. shortcuts */
  2388. for(i = 0; i < LEN(shortcuts); i++) {
  2389. if((ksym == shortcuts[i].keysym)
  2390. && (CLEANMASK(shortcuts[i].mod) == \
  2391. CLEANMASK(e->state))
  2392. && shortcuts[i].func) {
  2393. shortcuts[i].func(&(shortcuts[i].arg));
  2394. }
  2395. }
  2396. /* 2. custom keys from config.h */
  2397. if((customkey = kmap(ksym, e->state))) {
  2398. ttywrite(customkey, strlen(customkey));
  2399. /* 2. hardcoded (overrides X lookup) */
  2400. } else {
  2401. switch(ksym) {
  2402. case XK_Up:
  2403. case XK_Down:
  2404. case XK_Left:
  2405. case XK_Right:
  2406. /* XXX: shift up/down doesn't work */
  2407. sprintf(buf, "\033%c%c",
  2408. IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
  2409. (shift ? "dacb":"DACB")[ksym - XK_Left]);
  2410. ttywrite(buf, 3);
  2411. break;
  2412. case XK_Insert:
  2413. if(shift)
  2414. selpaste();
  2415. break;
  2416. case XK_Return:
  2417. if(meta)
  2418. ttywrite("\033", 1);
  2419. if(IS_SET(MODE_CRLF)) {
  2420. ttywrite("\r\n", 2);
  2421. } else {
  2422. ttywrite("\r", 1);
  2423. }
  2424. break;
  2425. /* 3. X lookup */
  2426. default:
  2427. if(len > 0) {
  2428. if(meta && len == 1)
  2429. ttywrite("\033", 1);
  2430. ttywrite(buf, len);
  2431. }
  2432. break;
  2433. }
  2434. }
  2435. }
  2436. void
  2437. cmessage(XEvent *e) {
  2438. /* See xembed specs
  2439. http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
  2440. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2441. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2442. xw.state |= WIN_FOCUSED;
  2443. xseturgency(0);
  2444. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2445. xw.state &= ~WIN_FOCUSED;
  2446. }
  2447. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  2448. /* Send SIGHUP to shell */
  2449. kill(pid, SIGHUP);
  2450. exit(EXIT_SUCCESS);
  2451. }
  2452. }
  2453. void
  2454. cresize(int width, int height)
  2455. {
  2456. int col, row;
  2457. if(width != 0)
  2458. xw.w = width;
  2459. if(height != 0)
  2460. xw.h = height;
  2461. col = (xw.w - 2*borderpx) / xw.cw;
  2462. row = (xw.h - 2*borderpx) / xw.ch;
  2463. tresize(col, row);
  2464. xresize(col, row);
  2465. ttyresize();
  2466. }
  2467. void
  2468. resize(XEvent *e) {
  2469. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2470. return;
  2471. cresize(e->xconfigure.width, e->xconfigure.height);
  2472. }
  2473. void
  2474. run(void) {
  2475. XEvent ev;
  2476. fd_set rfd;
  2477. int xfd = XConnectionNumber(xw.dpy), i;
  2478. struct timeval drawtimeout, *tv = NULL;
  2479. for(i = 0;; i++) {
  2480. FD_ZERO(&rfd);
  2481. FD_SET(cmdfd, &rfd);
  2482. FD_SET(xfd, &rfd);
  2483. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  2484. if(errno == EINTR)
  2485. continue;
  2486. die("select failed: %s\n", SERRNO);
  2487. }
  2488. /*
  2489. * Stop after a certain number of reads so the user does not
  2490. * feel like the system is stuttering.
  2491. */
  2492. if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
  2493. ttyread();
  2494. /*
  2495. * Just wait a bit so it isn't disturbing the
  2496. * user and the system is able to write something.
  2497. */
  2498. drawtimeout.tv_sec = 0;
  2499. drawtimeout.tv_usec = 5;
  2500. tv = &drawtimeout;
  2501. continue;
  2502. }
  2503. i = 0;
  2504. tv = NULL;
  2505. while(XPending(xw.dpy)) {
  2506. XNextEvent(xw.dpy, &ev);
  2507. if(XFilterEvent(&ev, None))
  2508. continue;
  2509. if(handler[ev.type])
  2510. (handler[ev.type])(&ev);
  2511. }
  2512. draw();
  2513. XFlush(xw.dpy);
  2514. }
  2515. }
  2516. int
  2517. main(int argc, char *argv[]) {
  2518. int i, bitm, xr, yr;
  2519. uint wr, hr;
  2520. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2521. xw.isfixed = False;
  2522. for(i = 1; i < argc; i++) {
  2523. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2524. case 'c':
  2525. if(++i < argc)
  2526. opt_class = argv[i];
  2527. break;
  2528. case 'e':
  2529. /* eat every remaining arguments */
  2530. if(++i < argc)
  2531. opt_cmd = &argv[i];
  2532. goto run;
  2533. case 'f':
  2534. if(++i < argc)
  2535. opt_font = argv[i];
  2536. break;
  2537. case 'g':
  2538. if(++i >= argc)
  2539. break;
  2540. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2541. if(bitm & XValue)
  2542. xw.fx = xr;
  2543. if(bitm & YValue)
  2544. xw.fy = yr;
  2545. if(bitm & WidthValue)
  2546. xw.fw = (int)wr;
  2547. if(bitm & HeightValue)
  2548. xw.fh = (int)hr;
  2549. if(bitm & XNegative && xw.fx == 0)
  2550. xw.fx = -1;
  2551. if(bitm & XNegative && xw.fy == 0)
  2552. xw.fy = -1;
  2553. if(xw.fh != 0 && xw.fw != 0)
  2554. xw.isfixed = True;
  2555. break;
  2556. case 'o':
  2557. if(++i < argc)
  2558. opt_io = argv[i];
  2559. break;
  2560. case 't':
  2561. if(++i < argc)
  2562. opt_title = argv[i];
  2563. break;
  2564. case 'v':
  2565. default:
  2566. die(USAGE);
  2567. case 'w':
  2568. if(++i < argc)
  2569. opt_embed = argv[i];
  2570. break;
  2571. }
  2572. }
  2573. run:
  2574. setlocale(LC_CTYPE, "");
  2575. XSetLocaleModifiers("");
  2576. tnew(80, 24);
  2577. xinit();
  2578. ttynew();
  2579. selinit();
  2580. run();
  2581. return 0;
  2582. }