st.c 74 KB

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