st.c 74 KB

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