st.c 68 KB

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