st.c 75 KB

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