st.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389
  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;
  1123. csiescseq.narg = 0;
  1124. if(*p == '?')
  1125. csiescseq.priv = 1, p++;
  1126. while(p < csiescseq.buf+csiescseq.len) {
  1127. while(isdigit(*p)) {
  1128. csiescseq.arg[csiescseq.narg] *= 10;
  1129. csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
  1130. }
  1131. if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
  1132. csiescseq.narg++, p++;
  1133. } else {
  1134. csiescseq.mode = *p;
  1135. csiescseq.narg++;
  1136. return;
  1137. }
  1138. }
  1139. }
  1140. /* for absolute user moves, when decom is set */
  1141. void
  1142. tmoveato(int x, int y) {
  1143. tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
  1144. }
  1145. void
  1146. tmoveto(int x, int y) {
  1147. int miny, maxy;
  1148. if(term.c.state & CURSOR_ORIGIN) {
  1149. miny = term.top;
  1150. maxy = term.bot;
  1151. } else {
  1152. miny = 0;
  1153. maxy = term.row - 1;
  1154. }
  1155. LIMIT(x, 0, term.col-1);
  1156. LIMIT(y, miny, maxy);
  1157. term.c.state &= ~CURSOR_WRAPNEXT;
  1158. term.c.x = x;
  1159. term.c.y = y;
  1160. }
  1161. void
  1162. tsetchar(char *c, Glyph *attr, int x, int y) {
  1163. static char *vt100_0[62] = { /* 0x41 - 0x7e */
  1164. "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
  1165. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  1166. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  1167. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  1168. "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
  1169. "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
  1170. "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
  1171. "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
  1172. };
  1173. /*
  1174. * The table is proudly stolen from rxvt.
  1175. */
  1176. if(attr->mode & ATTR_GFX) {
  1177. if(c[0] >= 0x41 && c[0] <= 0x7e
  1178. && vt100_0[c[0] - 0x41]) {
  1179. c = vt100_0[c[0] - 0x41];
  1180. }
  1181. }
  1182. term.dirty[y] = 1;
  1183. term.line[y][x] = *attr;
  1184. memcpy(term.line[y][x].c, c, UTF_SIZ);
  1185. term.line[y][x].state |= GLYPH_SET;
  1186. }
  1187. void
  1188. tclearregion(int x1, int y1, int x2, int y2, int bce) {
  1189. int x, y, temp;
  1190. if(x1 > x2)
  1191. temp = x1, x1 = x2, x2 = temp;
  1192. if(y1 > y2)
  1193. temp = y1, y1 = y2, y2 = temp;
  1194. LIMIT(x1, 0, term.col-1);
  1195. LIMIT(x2, 0, term.col-1);
  1196. LIMIT(y1, 0, term.row-1);
  1197. LIMIT(y2, 0, term.row-1);
  1198. for(y = y1; y <= y2; y++) {
  1199. term.dirty[y] = 1;
  1200. for(x = x1; x <= x2; x++) {
  1201. if(bce) {
  1202. term.line[y][x] = term.c.attr;
  1203. memcpy(term.line[y][x].c, " ", 2);
  1204. term.line[y][x].state |= GLYPH_SET;
  1205. } else {
  1206. term.line[y][x].state = 0;
  1207. }
  1208. }
  1209. }
  1210. }
  1211. void
  1212. tdeletechar(int n) {
  1213. int src = term.c.x + n;
  1214. int dst = term.c.x;
  1215. int size = term.col - src;
  1216. term.dirty[term.c.y] = 1;
  1217. if(src >= term.col) {
  1218. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
  1219. return;
  1220. }
  1221. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
  1222. size * sizeof(Glyph));
  1223. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y, 0);
  1224. }
  1225. void
  1226. tinsertblank(int n) {
  1227. int src = term.c.x;
  1228. int dst = src + n;
  1229. int size = term.col - dst;
  1230. term.dirty[term.c.y] = 1;
  1231. if(dst >= term.col) {
  1232. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
  1233. return;
  1234. }
  1235. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
  1236. size * sizeof(Glyph));
  1237. tclearregion(src, term.c.y, dst - 1, term.c.y, 0);
  1238. }
  1239. void
  1240. tinsertblankline(int n) {
  1241. if(term.c.y < term.top || term.c.y > term.bot)
  1242. return;
  1243. tscrolldown(term.c.y, n);
  1244. }
  1245. void
  1246. tdeleteline(int n) {
  1247. if(term.c.y < term.top || term.c.y > term.bot)
  1248. return;
  1249. tscrollup(term.c.y, n);
  1250. }
  1251. void
  1252. tsetattr(int *attr, int l) {
  1253. int i;
  1254. for(i = 0; i < l; i++) {
  1255. switch(attr[i]) {
  1256. case 0:
  1257. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
  1258. | ATTR_ITALIC | ATTR_BLINK);
  1259. term.c.attr.fg = defaultfg;
  1260. term.c.attr.bg = defaultbg;
  1261. break;
  1262. case 1:
  1263. term.c.attr.mode |= ATTR_BOLD;
  1264. break;
  1265. case 3:
  1266. term.c.attr.mode |= ATTR_ITALIC;
  1267. break;
  1268. case 4:
  1269. term.c.attr.mode |= ATTR_UNDERLINE;
  1270. break;
  1271. case 5: /* slow blink */
  1272. case 6: /* rapid blink */
  1273. term.c.attr.mode |= ATTR_BLINK;
  1274. break;
  1275. case 7:
  1276. term.c.attr.mode |= ATTR_REVERSE;
  1277. break;
  1278. case 21:
  1279. case 22:
  1280. term.c.attr.mode &= ~ATTR_BOLD;
  1281. break;
  1282. case 23:
  1283. term.c.attr.mode &= ~ATTR_ITALIC;
  1284. break;
  1285. case 24:
  1286. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1287. break;
  1288. case 25:
  1289. case 26:
  1290. term.c.attr.mode &= ~ATTR_BLINK;
  1291. break;
  1292. case 27:
  1293. term.c.attr.mode &= ~ATTR_REVERSE;
  1294. break;
  1295. case 38:
  1296. if(i + 2 < l && attr[i + 1] == 5) {
  1297. i += 2;
  1298. if(BETWEEN(attr[i], 0, 255)) {
  1299. term.c.attr.fg = attr[i];
  1300. } else {
  1301. fprintf(stderr,
  1302. "erresc: bad fgcolor %d\n",
  1303. attr[i]);
  1304. }
  1305. } else {
  1306. fprintf(stderr,
  1307. "erresc(38): gfx attr %d unknown\n",
  1308. attr[i]);
  1309. }
  1310. break;
  1311. case 39:
  1312. term.c.attr.fg = defaultfg;
  1313. break;
  1314. case 48:
  1315. if(i + 2 < l && attr[i + 1] == 5) {
  1316. i += 2;
  1317. if(BETWEEN(attr[i], 0, 255)) {
  1318. term.c.attr.bg = attr[i];
  1319. } else {
  1320. fprintf(stderr,
  1321. "erresc: bad bgcolor %d\n",
  1322. attr[i]);
  1323. }
  1324. } else {
  1325. fprintf(stderr,
  1326. "erresc(48): gfx attr %d unknown\n",
  1327. attr[i]);
  1328. }
  1329. break;
  1330. case 49:
  1331. term.c.attr.bg = defaultbg;
  1332. break;
  1333. default:
  1334. if(BETWEEN(attr[i], 30, 37)) {
  1335. term.c.attr.fg = attr[i] - 30;
  1336. } else if(BETWEEN(attr[i], 40, 47)) {
  1337. term.c.attr.bg = attr[i] - 40;
  1338. } else if(BETWEEN(attr[i], 90, 97)) {
  1339. term.c.attr.fg = attr[i] - 90 + 8;
  1340. } else if(BETWEEN(attr[i], 100, 107)) {
  1341. term.c.attr.bg = attr[i] - 100 + 8;
  1342. } else {
  1343. fprintf(stderr,
  1344. "erresc(default): gfx attr %d unknown\n",
  1345. attr[i]), csidump();
  1346. }
  1347. break;
  1348. }
  1349. }
  1350. }
  1351. void
  1352. tsetscroll(int t, int b) {
  1353. int temp;
  1354. LIMIT(t, 0, term.row-1);
  1355. LIMIT(b, 0, term.row-1);
  1356. if(t > b) {
  1357. temp = t;
  1358. t = b;
  1359. b = temp;
  1360. }
  1361. term.top = t;
  1362. term.bot = b;
  1363. }
  1364. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1365. void
  1366. tsetmode(bool priv, bool set, int *args, int narg) {
  1367. int *lim, mode;
  1368. bool alt;
  1369. for(lim = args + narg; args < lim; ++args) {
  1370. if(priv) {
  1371. switch(*args) {
  1372. break;
  1373. case 1: /* DECCKM -- Cursor key */
  1374. MODBIT(term.mode, set, MODE_APPCURSOR);
  1375. break;
  1376. case 5: /* DECSCNM -- Reverse video */
  1377. mode = term.mode;
  1378. MODBIT(term.mode, set, MODE_REVERSE);
  1379. if(mode != term.mode)
  1380. redraw(REDRAW_TIMEOUT);
  1381. break;
  1382. case 6: /* DECOM -- Origin */
  1383. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1384. tmoveato(0, 0);
  1385. break;
  1386. case 7: /* DECAWM -- Auto wrap */
  1387. MODBIT(term.mode, set, MODE_WRAP);
  1388. break;
  1389. case 0: /* Error (IGNORED) */
  1390. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1391. case 3: /* DECCOLM -- Column (IGNORED) */
  1392. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1393. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1394. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1395. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1396. case 42: /* DECNRCM -- National characters (IGNORED) */
  1397. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1398. break;
  1399. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1400. MODBIT(term.mode, !set, MODE_HIDE);
  1401. break;
  1402. case 1000: /* 1000,1002: enable xterm mouse report */
  1403. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1404. MODBIT(term.mode, 0, MODE_MOUSEMOTION);
  1405. break;
  1406. case 1002:
  1407. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1408. MODBIT(term.mode, 0, MODE_MOUSEBTN);
  1409. break;
  1410. case 1006:
  1411. MODBIT(term.mode, set, MODE_MOUSESGR);
  1412. break;
  1413. case 1049: /* = 1047 and 1048 */
  1414. case 47:
  1415. case 1047: {
  1416. alt = IS_SET(MODE_ALTSCREEN);
  1417. if(alt) {
  1418. tclearregion(0, 0, term.col-1,
  1419. term.row-1, 0);
  1420. }
  1421. if(set ^ alt) /* set is always 1 or 0 */
  1422. tswapscreen();
  1423. if(*args != 1049)
  1424. break;
  1425. }
  1426. /* pass through */
  1427. case 1048:
  1428. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1429. break;
  1430. default:
  1431. fprintf(stderr,
  1432. "erresc: unknown private set/reset mode %d\n",
  1433. *args);
  1434. break;
  1435. }
  1436. } else {
  1437. switch(*args) {
  1438. case 0: /* Error (IGNORED) */
  1439. break;
  1440. case 2: /* KAM -- keyboard action */
  1441. MODBIT(term.mode, set, MODE_KBDLOCK);
  1442. break;
  1443. case 4: /* IRM -- Insertion-replacement */
  1444. MODBIT(term.mode, set, MODE_INSERT);
  1445. break;
  1446. case 12: /* SRM -- Send/Receive */
  1447. MODBIT(term.mode, !set, MODE_ECHO);
  1448. break;
  1449. case 20: /* LNM -- Linefeed/new line */
  1450. MODBIT(term.mode, set, MODE_CRLF);
  1451. break;
  1452. default:
  1453. fprintf(stderr,
  1454. "erresc: unknown set/reset mode %d\n",
  1455. *args);
  1456. break;
  1457. }
  1458. }
  1459. }
  1460. }
  1461. #undef MODBIT
  1462. void
  1463. csihandle(void) {
  1464. switch(csiescseq.mode) {
  1465. default:
  1466. unknown:
  1467. fprintf(stderr, "erresc: unknown csi ");
  1468. csidump();
  1469. /* die(""); */
  1470. break;
  1471. case '@': /* ICH -- Insert <n> blank char */
  1472. DEFAULT(csiescseq.arg[0], 1);
  1473. tinsertblank(csiescseq.arg[0]);
  1474. break;
  1475. case 'A': /* CUU -- Cursor <n> Up */
  1476. DEFAULT(csiescseq.arg[0], 1);
  1477. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1478. break;
  1479. case 'B': /* CUD -- Cursor <n> Down */
  1480. case 'e': /* VPR --Cursor <n> Down */
  1481. DEFAULT(csiescseq.arg[0], 1);
  1482. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1483. break;
  1484. case 'c': /* DA -- Device Attributes */
  1485. if(csiescseq.arg[0] == 0)
  1486. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1487. break;
  1488. case 'C': /* CUF -- Cursor <n> Forward */
  1489. case 'a': /* HPR -- Cursor <n> Forward */
  1490. DEFAULT(csiescseq.arg[0], 1);
  1491. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1492. break;
  1493. case 'D': /* CUB -- Cursor <n> Backward */
  1494. DEFAULT(csiescseq.arg[0], 1);
  1495. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1496. break;
  1497. case 'E': /* CNL -- Cursor <n> Down and first col */
  1498. DEFAULT(csiescseq.arg[0], 1);
  1499. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1500. break;
  1501. case 'F': /* CPL -- Cursor <n> Up and first col */
  1502. DEFAULT(csiescseq.arg[0], 1);
  1503. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1504. break;
  1505. case 'g': /* TBC -- Tabulation clear */
  1506. switch(csiescseq.arg[0]) {
  1507. case 0: /* clear current tab stop */
  1508. term.tabs[term.c.x] = 0;
  1509. break;
  1510. case 3: /* clear all the tabs */
  1511. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1512. break;
  1513. default:
  1514. goto unknown;
  1515. }
  1516. break;
  1517. case 'G': /* CHA -- Move to <col> */
  1518. case '`': /* HPA */
  1519. DEFAULT(csiescseq.arg[0], 1);
  1520. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1521. break;
  1522. case 'H': /* CUP -- Move to <row> <col> */
  1523. case 'f': /* HVP */
  1524. DEFAULT(csiescseq.arg[0], 1);
  1525. DEFAULT(csiescseq.arg[1], 1);
  1526. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1527. break;
  1528. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1529. DEFAULT(csiescseq.arg[0], 1);
  1530. while(csiescseq.arg[0]--)
  1531. tputtab(1);
  1532. break;
  1533. case 'J': /* ED -- Clear screen */
  1534. sel.bx = -1;
  1535. switch(csiescseq.arg[0]) {
  1536. case 0: /* below */
  1537. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
  1538. if(term.c.y < term.row-1) {
  1539. tclearregion(0, term.c.y+1, term.col-1,
  1540. term.row-1, 1);
  1541. }
  1542. break;
  1543. case 1: /* above */
  1544. if(term.c.y > 1)
  1545. tclearregion(0, 0, term.col-1, term.c.y-1, 1);
  1546. tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
  1547. break;
  1548. case 2: /* all */
  1549. tclearregion(0, 0, term.col-1, term.row-1, 1);
  1550. break;
  1551. default:
  1552. goto unknown;
  1553. }
  1554. break;
  1555. case 'K': /* EL -- Clear line */
  1556. switch(csiescseq.arg[0]) {
  1557. case 0: /* right */
  1558. tclearregion(term.c.x, term.c.y, term.col-1,
  1559. term.c.y, 1);
  1560. break;
  1561. case 1: /* left */
  1562. tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
  1563. break;
  1564. case 2: /* all */
  1565. tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
  1566. break;
  1567. }
  1568. break;
  1569. case 'S': /* SU -- Scroll <n> line up */
  1570. DEFAULT(csiescseq.arg[0], 1);
  1571. tscrollup(term.top, csiescseq.arg[0]);
  1572. break;
  1573. case 'T': /* SD -- Scroll <n> line down */
  1574. DEFAULT(csiescseq.arg[0], 1);
  1575. tscrolldown(term.top, csiescseq.arg[0]);
  1576. break;
  1577. case 'L': /* IL -- Insert <n> blank lines */
  1578. DEFAULT(csiescseq.arg[0], 1);
  1579. tinsertblankline(csiescseq.arg[0]);
  1580. break;
  1581. case 'l': /* RM -- Reset Mode */
  1582. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1583. break;
  1584. case 'M': /* DL -- Delete <n> lines */
  1585. DEFAULT(csiescseq.arg[0], 1);
  1586. tdeleteline(csiescseq.arg[0]);
  1587. break;
  1588. case 'X': /* ECH -- Erase <n> char */
  1589. DEFAULT(csiescseq.arg[0], 1);
  1590. tclearregion(term.c.x, term.c.y,
  1591. term.c.x + csiescseq.arg[0] - 1, term.c.y, 1);
  1592. break;
  1593. case 'P': /* DCH -- Delete <n> char */
  1594. DEFAULT(csiescseq.arg[0], 1);
  1595. tdeletechar(csiescseq.arg[0]);
  1596. break;
  1597. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1598. DEFAULT(csiescseq.arg[0], 1);
  1599. while(csiescseq.arg[0]--)
  1600. tputtab(0);
  1601. break;
  1602. case 'd': /* VPA -- Move to <row> */
  1603. DEFAULT(csiescseq.arg[0], 1);
  1604. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1605. break;
  1606. case 'h': /* SM -- Set terminal mode */
  1607. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1608. break;
  1609. case 'm': /* SGR -- Terminal attribute (color) */
  1610. tsetattr(csiescseq.arg, csiescseq.narg);
  1611. break;
  1612. case 'r': /* DECSTBM -- Set Scrolling Region */
  1613. if(csiescseq.priv) {
  1614. goto unknown;
  1615. } else {
  1616. DEFAULT(csiescseq.arg[0], 1);
  1617. DEFAULT(csiescseq.arg[1], term.row);
  1618. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1619. tmoveato(0, 0);
  1620. }
  1621. break;
  1622. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1623. tcursor(CURSOR_SAVE);
  1624. break;
  1625. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1626. tcursor(CURSOR_LOAD);
  1627. break;
  1628. }
  1629. }
  1630. void
  1631. csidump(void) {
  1632. int i;
  1633. uint c;
  1634. printf("ESC[");
  1635. for(i = 0; i < csiescseq.len; i++) {
  1636. c = csiescseq.buf[i] & 0xff;
  1637. if(isprint(c)) {
  1638. putchar(c);
  1639. } else if(c == '\n') {
  1640. printf("(\\n)");
  1641. } else if(c == '\r') {
  1642. printf("(\\r)");
  1643. } else if(c == 0x1b) {
  1644. printf("(\\e)");
  1645. } else {
  1646. printf("(%02x)", c);
  1647. }
  1648. }
  1649. putchar('\n');
  1650. }
  1651. void
  1652. csireset(void) {
  1653. memset(&csiescseq, 0, sizeof(csiescseq));
  1654. }
  1655. void
  1656. strhandle(void) {
  1657. char *p = NULL;
  1658. int i, j, narg;
  1659. strparse();
  1660. narg = strescseq.narg;
  1661. switch(strescseq.type) {
  1662. case ']': /* OSC -- Operating System Command */
  1663. switch(i = atoi(strescseq.args[0])) {
  1664. case 0:
  1665. case 1:
  1666. case 2:
  1667. if(narg > 1)
  1668. xsettitle(strescseq.args[1]);
  1669. break;
  1670. case 4: /* color set */
  1671. if(narg < 3)
  1672. break;
  1673. p = strescseq.args[2];
  1674. /* fall through */
  1675. case 104: /* color reset, here p = NULL */
  1676. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  1677. if (!xsetcolorname(j, p)) {
  1678. fprintf(stderr, "erresc: invalid color %s\n", p);
  1679. } else {
  1680. /*
  1681. * TODO if defaultbg color is changed, borders
  1682. * are dirty
  1683. */
  1684. redraw(0);
  1685. }
  1686. break;
  1687. default:
  1688. fprintf(stderr, "erresc: unknown str ");
  1689. strdump();
  1690. break;
  1691. }
  1692. break;
  1693. case 'k': /* old title set compatibility */
  1694. xsettitle(strescseq.args[0]);
  1695. break;
  1696. case 'P': /* DSC -- Device Control String */
  1697. case '_': /* APC -- Application Program Command */
  1698. case '^': /* PM -- Privacy Message */
  1699. default:
  1700. fprintf(stderr, "erresc: unknown str ");
  1701. strdump();
  1702. /* die(""); */
  1703. break;
  1704. }
  1705. }
  1706. void
  1707. strparse(void) {
  1708. /*
  1709. * TODO: Implement parsing like for CSI when required.
  1710. * Format: ESC type cmd ';' arg0 [';' argn] ESC \
  1711. */
  1712. int narg = 0;
  1713. char *start = strescseq.buf, *end = start + strescseq.len;
  1714. strescseq.args[0] = start;
  1715. while(start < end && narg < LEN(strescseq.args)) {
  1716. start = memchr(start, ';', end - start);
  1717. if(!start)
  1718. break;
  1719. *start++ = '\0';
  1720. if(start < end) {
  1721. strescseq.args[++narg] = start;
  1722. }
  1723. }
  1724. strescseq.narg = narg + 1;
  1725. }
  1726. void
  1727. strdump(void) {
  1728. int i;
  1729. uint c;
  1730. printf("ESC%c", strescseq.type);
  1731. for(i = 0; i < strescseq.len; i++) {
  1732. c = strescseq.buf[i] & 0xff;
  1733. if(isprint(c)) {
  1734. putchar(c);
  1735. } else if(c == '\n') {
  1736. printf("(\\n)");
  1737. } else if(c == '\r') {
  1738. printf("(\\r)");
  1739. } else if(c == 0x1b) {
  1740. printf("(\\e)");
  1741. } else {
  1742. printf("(%02x)", c);
  1743. }
  1744. }
  1745. printf("ESC\\\n");
  1746. }
  1747. void
  1748. strreset(void) {
  1749. memset(&strescseq, 0, sizeof(strescseq));
  1750. }
  1751. void
  1752. tputtab(bool forward) {
  1753. uint x = term.c.x;
  1754. if(forward) {
  1755. if(x == term.col)
  1756. return;
  1757. for(++x; x < term.col && !term.tabs[x]; ++x)
  1758. /* nothing */ ;
  1759. } else {
  1760. if(x == 0)
  1761. return;
  1762. for(--x; x > 0 && !term.tabs[x]; --x)
  1763. /* nothing */ ;
  1764. }
  1765. tmoveto(x, term.c.y);
  1766. }
  1767. void
  1768. techo(char *buf, int len) {
  1769. for(; len > 0; buf++, len--) {
  1770. char c = *buf;
  1771. if(c == '\033') { /* escape */
  1772. tputc("^", 1);
  1773. tputc("[", 1);
  1774. } else if(c < '\x20') { /* control code */
  1775. if(c != '\n' && c != '\r' && c != '\t') {
  1776. c |= '\x40';
  1777. tputc("^", 1);
  1778. }
  1779. tputc(&c, 1);
  1780. } else {
  1781. break;
  1782. }
  1783. }
  1784. if(len)
  1785. tputc(buf, len);
  1786. }
  1787. void
  1788. tputc(char *c, int len) {
  1789. uchar ascii = *c;
  1790. bool control = ascii < '\x20' || ascii == 0177;
  1791. if(iofd != -1) {
  1792. if(xwrite(iofd, c, len) < 0) {
  1793. fprintf(stderr, "Error writing in %s:%s\n",
  1794. opt_io, strerror(errno));
  1795. close(iofd);
  1796. iofd = -1;
  1797. }
  1798. }
  1799. /*
  1800. * STR sequences must be checked before anything else
  1801. * because it can use some control codes as part of the sequence.
  1802. */
  1803. if(term.esc & ESC_STR) {
  1804. switch(ascii) {
  1805. case '\033':
  1806. term.esc = ESC_START | ESC_STR_END;
  1807. break;
  1808. case '\a': /* backwards compatibility to xterm */
  1809. term.esc = 0;
  1810. strhandle();
  1811. break;
  1812. default:
  1813. if(strescseq.len + len < sizeof(strescseq.buf)) {
  1814. memmove(&strescseq.buf[strescseq.len], c, len);
  1815. strescseq.len += len;
  1816. } else {
  1817. /*
  1818. * Here is a bug in terminals. If the user never sends
  1819. * some code to stop the str or esc command, then st
  1820. * will stop responding. But this is better than
  1821. * silently failing with unknown characters. At least
  1822. * then users will report back.
  1823. *
  1824. * In the case users ever get fixed, here is the code:
  1825. */
  1826. /*
  1827. * term.esc = 0;
  1828. * strhandle();
  1829. */
  1830. }
  1831. }
  1832. return;
  1833. }
  1834. /*
  1835. * Actions of control codes must be performed as soon they arrive
  1836. * because they can be embedded inside a control sequence, and
  1837. * they must not cause conflicts with sequences.
  1838. */
  1839. if(control) {
  1840. switch(ascii) {
  1841. case '\t': /* HT */
  1842. tputtab(1);
  1843. return;
  1844. case '\b': /* BS */
  1845. tmoveto(term.c.x-1, term.c.y);
  1846. return;
  1847. case '\r': /* CR */
  1848. tmoveto(0, term.c.y);
  1849. return;
  1850. case '\f': /* LF */
  1851. case '\v': /* VT */
  1852. case '\n': /* LF */
  1853. /* go to first col if the mode is set */
  1854. tnewline(IS_SET(MODE_CRLF));
  1855. return;
  1856. case '\a': /* BEL */
  1857. if(!(xw.state & WIN_FOCUSED))
  1858. xseturgency(1);
  1859. return;
  1860. case '\033': /* ESC */
  1861. csireset();
  1862. term.esc = ESC_START;
  1863. return;
  1864. case '\016': /* SO */
  1865. case '\017': /* SI */
  1866. /*
  1867. * Different charsets are hard to handle. Applications
  1868. * should use the right alt charset escapes for the
  1869. * only reason they still exist: line drawing. The
  1870. * rest is incompatible history st should not support.
  1871. */
  1872. return;
  1873. case '\032': /* SUB */
  1874. case '\030': /* CAN */
  1875. csireset();
  1876. return;
  1877. case '\005': /* ENQ (IGNORED) */
  1878. case '\000': /* NUL (IGNORED) */
  1879. case '\021': /* XON (IGNORED) */
  1880. case '\023': /* XOFF (IGNORED) */
  1881. case 0177: /* DEL (IGNORED) */
  1882. return;
  1883. }
  1884. } else if(term.esc & ESC_START) {
  1885. if(term.esc & ESC_CSI) {
  1886. csiescseq.buf[csiescseq.len++] = ascii;
  1887. if(BETWEEN(ascii, 0x40, 0x7E)
  1888. || csiescseq.len >= ESC_BUF_SIZ) {
  1889. term.esc = 0;
  1890. csiparse(), csihandle();
  1891. }
  1892. } else if(term.esc & ESC_STR_END) {
  1893. term.esc = 0;
  1894. if(ascii == '\\')
  1895. strhandle();
  1896. } else if(term.esc & ESC_ALTCHARSET) {
  1897. switch(ascii) {
  1898. case '0': /* Line drawing set */
  1899. term.c.attr.mode |= ATTR_GFX;
  1900. break;
  1901. case 'B': /* USASCII */
  1902. term.c.attr.mode &= ~ATTR_GFX;
  1903. break;
  1904. case 'A': /* UK (IGNORED) */
  1905. case '<': /* multinational charset (IGNORED) */
  1906. case '5': /* Finnish (IGNORED) */
  1907. case 'C': /* Finnish (IGNORED) */
  1908. case 'K': /* German (IGNORED) */
  1909. break;
  1910. default:
  1911. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  1912. }
  1913. term.esc = 0;
  1914. } else if(term.esc & ESC_TEST) {
  1915. if(ascii == '8') { /* DEC screen alignment test. */
  1916. char E[UTF_SIZ] = "E";
  1917. int x, y;
  1918. for(x = 0; x < term.col; ++x) {
  1919. for(y = 0; y < term.row; ++y)
  1920. tsetchar(E, &term.c.attr, x, y);
  1921. }
  1922. }
  1923. term.esc = 0;
  1924. } else {
  1925. switch(ascii) {
  1926. case '[':
  1927. term.esc |= ESC_CSI;
  1928. break;
  1929. case '#':
  1930. term.esc |= ESC_TEST;
  1931. break;
  1932. case 'P': /* DCS -- Device Control String */
  1933. case '_': /* APC -- Application Program Command */
  1934. case '^': /* PM -- Privacy Message */
  1935. case ']': /* OSC -- Operating System Command */
  1936. case 'k': /* old title set compatibility */
  1937. strreset();
  1938. strescseq.type = ascii;
  1939. term.esc |= ESC_STR;
  1940. break;
  1941. case '(': /* set primary charset G0 */
  1942. term.esc |= ESC_ALTCHARSET;
  1943. break;
  1944. case ')': /* set secondary charset G1 (IGNORED) */
  1945. case '*': /* set tertiary charset G2 (IGNORED) */
  1946. case '+': /* set quaternary charset G3 (IGNORED) */
  1947. term.esc = 0;
  1948. break;
  1949. case 'D': /* IND -- Linefeed */
  1950. if(term.c.y == term.bot) {
  1951. tscrollup(term.top, 1);
  1952. } else {
  1953. tmoveto(term.c.x, term.c.y+1);
  1954. }
  1955. term.esc = 0;
  1956. break;
  1957. case 'E': /* NEL -- Next line */
  1958. tnewline(1); /* always go to first col */
  1959. term.esc = 0;
  1960. break;
  1961. case 'H': /* HTS -- Horizontal tab stop */
  1962. term.tabs[term.c.x] = 1;
  1963. term.esc = 0;
  1964. break;
  1965. case 'M': /* RI -- Reverse index */
  1966. if(term.c.y == term.top) {
  1967. tscrolldown(term.top, 1);
  1968. } else {
  1969. tmoveto(term.c.x, term.c.y-1);
  1970. }
  1971. term.esc = 0;
  1972. break;
  1973. case 'Z': /* DECID -- Identify Terminal */
  1974. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1975. term.esc = 0;
  1976. break;
  1977. case 'c': /* RIS -- Reset to inital state */
  1978. treset();
  1979. term.esc = 0;
  1980. xresettitle();
  1981. break;
  1982. case '=': /* DECPAM -- Application keypad */
  1983. term.mode |= MODE_APPKEYPAD;
  1984. term.esc = 0;
  1985. break;
  1986. case '>': /* DECPNM -- Normal keypad */
  1987. term.mode &= ~MODE_APPKEYPAD;
  1988. term.esc = 0;
  1989. break;
  1990. case '7': /* DECSC -- Save Cursor */
  1991. tcursor(CURSOR_SAVE);
  1992. term.esc = 0;
  1993. break;
  1994. case '8': /* DECRC -- Restore Cursor */
  1995. tcursor(CURSOR_LOAD);
  1996. term.esc = 0;
  1997. break;
  1998. case '\\': /* ST -- Stop */
  1999. term.esc = 0;
  2000. break;
  2001. default:
  2002. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2003. (uchar) ascii, isprint(ascii)? ascii:'.');
  2004. term.esc = 0;
  2005. }
  2006. }
  2007. /*
  2008. * All characters which form part of a sequence are not
  2009. * printed
  2010. */
  2011. return;
  2012. }
  2013. /*
  2014. * Display control codes only if we are in graphic mode
  2015. */
  2016. if(control && !(term.c.attr.mode & ATTR_GFX))
  2017. return;
  2018. if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
  2019. sel.bx = -1;
  2020. if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
  2021. tnewline(1); /* always go to first col */
  2022. if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
  2023. memmove(&term.line[term.c.y][term.c.x+1],
  2024. &term.line[term.c.y][term.c.x],
  2025. (term.col - term.c.x - 1) * sizeof(Glyph));
  2026. }
  2027. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  2028. if(term.c.x+1 < term.col) {
  2029. tmoveto(term.c.x+1, term.c.y);
  2030. } else {
  2031. term.c.state |= CURSOR_WRAPNEXT;
  2032. }
  2033. }
  2034. int
  2035. tresize(int col, int row) {
  2036. int i, x;
  2037. int minrow = MIN(row, term.row);
  2038. int mincol = MIN(col, term.col);
  2039. int slide = term.c.y - row + 1;
  2040. bool *bp;
  2041. if(col < 1 || row < 1)
  2042. return 0;
  2043. /* free unneeded rows */
  2044. i = 0;
  2045. if(slide > 0) {
  2046. /*
  2047. * slide screen to keep cursor where we expect it -
  2048. * tscrollup would work here, but we can optimize to
  2049. * memmove because we're freeing the earlier lines
  2050. */
  2051. for(/* i = 0 */; i < slide; i++) {
  2052. free(term.line[i]);
  2053. free(term.alt[i]);
  2054. }
  2055. memmove(term.line, term.line + slide, row * sizeof(Line));
  2056. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  2057. }
  2058. for(i += row; i < term.row; i++) {
  2059. free(term.line[i]);
  2060. free(term.alt[i]);
  2061. }
  2062. /* resize to new height */
  2063. term.line = xrealloc(term.line, row * sizeof(Line));
  2064. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2065. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2066. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2067. /* resize each row to new width, zero-pad if needed */
  2068. for(i = 0; i < minrow; i++) {
  2069. term.dirty[i] = 1;
  2070. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2071. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2072. for(x = mincol; x < col; x++) {
  2073. term.line[i][x].state = 0;
  2074. term.alt[i][x].state = 0;
  2075. }
  2076. }
  2077. /* allocate any new rows */
  2078. for(/* i == minrow */; i < row; i++) {
  2079. term.dirty[i] = 1;
  2080. term.line[i] = xcalloc(col, sizeof(Glyph));
  2081. term.alt [i] = xcalloc(col, sizeof(Glyph));
  2082. }
  2083. if(col > term.col) {
  2084. bp = term.tabs + term.col;
  2085. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2086. while(--bp > term.tabs && !*bp)
  2087. /* nothing */ ;
  2088. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2089. *bp = 1;
  2090. }
  2091. /* update terminal size */
  2092. term.col = col;
  2093. term.row = row;
  2094. /* reset scrolling region */
  2095. tsetscroll(0, row-1);
  2096. /* make use of the LIMIT in tmoveto */
  2097. tmoveto(term.c.x, term.c.y);
  2098. return (slide > 0);
  2099. }
  2100. void
  2101. xresize(int col, int row) {
  2102. xw.tw = MAX(1, col * xw.cw);
  2103. xw.th = MAX(1, row * xw.ch);
  2104. XFreePixmap(xw.dpy, xw.buf);
  2105. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2106. DefaultDepth(xw.dpy, xw.scr));
  2107. XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
  2108. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2109. XftDrawChange(xw.draw, xw.buf);
  2110. }
  2111. static inline ushort
  2112. sixd_to_16bit(int x) {
  2113. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  2114. }
  2115. void
  2116. xloadcols(void) {
  2117. int i, r, g, b;
  2118. XRenderColor color = { .alpha = 0xffff };
  2119. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  2120. for(i = 0; i < LEN(colorname); i++) {
  2121. if(!colorname[i])
  2122. continue;
  2123. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
  2124. die("Could not allocate color '%s'\n", colorname[i]);
  2125. }
  2126. }
  2127. /* load colors [16-255] ; same colors as xterm */
  2128. for(i = 16, r = 0; r < 6; r++) {
  2129. for(g = 0; g < 6; g++) {
  2130. for(b = 0; b < 6; b++) {
  2131. color.red = sixd_to_16bit(r);
  2132. color.green = sixd_to_16bit(g);
  2133. color.blue = sixd_to_16bit(b);
  2134. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
  2135. die("Could not allocate color %d\n", i);
  2136. }
  2137. i++;
  2138. }
  2139. }
  2140. }
  2141. for(r = 0; r < 24; r++, i++) {
  2142. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  2143. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
  2144. &dc.col[i])) {
  2145. die("Could not allocate color %d\n", i);
  2146. }
  2147. }
  2148. }
  2149. int
  2150. xsetcolorname(int x, const char *name) {
  2151. XRenderColor color = { .alpha = 0xffff };
  2152. Colour colour;
  2153. if (x < 0 || x > LEN(colorname))
  2154. return -1;
  2155. if(!name) {
  2156. if(16 <= x && x < 16 + 216) {
  2157. int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
  2158. color.red = sixd_to_16bit(r);
  2159. color.green = sixd_to_16bit(g);
  2160. color.blue = sixd_to_16bit(b);
  2161. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
  2162. return 0; /* something went wrong */
  2163. dc.col[x] = colour;
  2164. return 1;
  2165. } else if (16 + 216 <= x && x < 256) {
  2166. color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
  2167. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
  2168. return 0; /* something went wrong */
  2169. dc.col[x] = colour;
  2170. return 1;
  2171. } else {
  2172. name = colorname[x];
  2173. }
  2174. }
  2175. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
  2176. return 0;
  2177. dc.col[x] = colour;
  2178. return 1;
  2179. }
  2180. void
  2181. xtermclear(int col1, int row1, int col2, int row2) {
  2182. XftDrawRect(xw.draw,
  2183. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2184. borderpx + col1 * xw.cw,
  2185. borderpx + row1 * xw.ch,
  2186. (col2-col1+1) * xw.cw,
  2187. (row2-row1+1) * xw.ch);
  2188. }
  2189. /*
  2190. * Absolute coordinates.
  2191. */
  2192. void
  2193. xclear(int x1, int y1, int x2, int y2) {
  2194. XftDrawRect(xw.draw,
  2195. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  2196. x1, y1, x2-x1, y2-y1);
  2197. }
  2198. void
  2199. xhints(void) {
  2200. XClassHint class = {opt_class ? opt_class : termname, termname};
  2201. XWMHints wm = {.flags = InputHint, .input = 1};
  2202. XSizeHints *sizeh = NULL;
  2203. sizeh = XAllocSizeHints();
  2204. if(xw.isfixed == False) {
  2205. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2206. sizeh->height = xw.h;
  2207. sizeh->width = xw.w;
  2208. sizeh->height_inc = xw.ch;
  2209. sizeh->width_inc = xw.cw;
  2210. sizeh->base_height = 2 * borderpx;
  2211. sizeh->base_width = 2 * borderpx;
  2212. } else {
  2213. sizeh->flags = PMaxSize | PMinSize;
  2214. sizeh->min_width = sizeh->max_width = xw.fw;
  2215. sizeh->min_height = sizeh->max_height = xw.fh;
  2216. }
  2217. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  2218. XFree(sizeh);
  2219. }
  2220. int
  2221. xloadfont(Font *f, FcPattern *pattern) {
  2222. FcPattern *match;
  2223. FcResult result;
  2224. match = FcFontMatch(NULL, pattern, &result);
  2225. if(!match)
  2226. return 1;
  2227. if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
  2228. FcPatternDestroy(match);
  2229. return 1;
  2230. }
  2231. if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  2232. FcPatternDestroy(match);
  2233. return 1;
  2234. }
  2235. f->pattern = FcPatternDuplicate(pattern);
  2236. f->ascent = f->match->ascent;
  2237. f->descent = f->match->descent;
  2238. f->lbearing = 0;
  2239. f->rbearing = f->match->max_advance_width;
  2240. f->height = f->match->height;
  2241. f->width = f->lbearing + f->rbearing;
  2242. return 0;
  2243. }
  2244. void
  2245. xloadfonts(char *fontstr, int fontsize) {
  2246. FcPattern *pattern;
  2247. FcResult result;
  2248. double fontval;
  2249. if(fontstr[0] == '-') {
  2250. pattern = XftXlfdParse(fontstr, False, False);
  2251. } else {
  2252. pattern = FcNameParse((FcChar8 *)fontstr);
  2253. }
  2254. if(!pattern)
  2255. die("st: can't open font %s\n", fontstr);
  2256. if(fontsize > 0) {
  2257. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2258. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2259. usedfontsize = fontsize;
  2260. } else {
  2261. result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2262. if(result == FcResultMatch) {
  2263. usedfontsize = (int)fontval;
  2264. } else {
  2265. /*
  2266. * Default font size is 12, if none given. This is to
  2267. * have a known usedfontsize value.
  2268. */
  2269. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2270. usedfontsize = 12;
  2271. }
  2272. }
  2273. FcConfigSubstitute(0, pattern, FcMatchPattern);
  2274. FcDefaultSubstitute(pattern);
  2275. if(xloadfont(&dc.font, pattern))
  2276. die("st: can't open font %s\n", fontstr);
  2277. /* Setting character width and height. */
  2278. xw.cw = dc.font.width;
  2279. xw.ch = dc.font.height;
  2280. FcPatternDel(pattern, FC_SLANT);
  2281. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2282. if(xloadfont(&dc.ifont, pattern))
  2283. die("st: can't open font %s\n", fontstr);
  2284. FcPatternDel(pattern, FC_WEIGHT);
  2285. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2286. if(xloadfont(&dc.ibfont, pattern))
  2287. die("st: can't open font %s\n", fontstr);
  2288. FcPatternDel(pattern, FC_SLANT);
  2289. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  2290. if(xloadfont(&dc.bfont, pattern))
  2291. die("st: can't open font %s\n", fontstr);
  2292. FcPatternDestroy(pattern);
  2293. }
  2294. void
  2295. xunloadfonts(void) {
  2296. int i, ip;
  2297. /*
  2298. * Free the loaded fonts in the font cache. This is done backwards
  2299. * from the frccur.
  2300. */
  2301. for(i = 0, ip = frccur; i < frclen; i++, ip--) {
  2302. if(ip < 0)
  2303. ip = LEN(frc) - 1;
  2304. XftFontClose(xw.dpy, frc[ip].font);
  2305. }
  2306. frccur = -1;
  2307. frclen = 0;
  2308. XftFontClose(xw.dpy, dc.font.match);
  2309. FcPatternDestroy(dc.font.pattern);
  2310. FcFontSetDestroy(dc.font.set);
  2311. XftFontClose(xw.dpy, dc.bfont.match);
  2312. FcPatternDestroy(dc.bfont.pattern);
  2313. FcFontSetDestroy(dc.bfont.set);
  2314. XftFontClose(xw.dpy, dc.ifont.match);
  2315. FcPatternDestroy(dc.ifont.pattern);
  2316. FcFontSetDestroy(dc.ifont.set);
  2317. XftFontClose(xw.dpy, dc.ibfont.match);
  2318. FcPatternDestroy(dc.ibfont.pattern);
  2319. FcFontSetDestroy(dc.ibfont.set);
  2320. }
  2321. void
  2322. xzoom(const Arg *arg) {
  2323. xunloadfonts();
  2324. xloadfonts(usedfont, usedfontsize + arg->i);
  2325. cresize(0, 0);
  2326. redraw(0);
  2327. }
  2328. void
  2329. xinit(void) {
  2330. XSetWindowAttributes attrs;
  2331. XGCValues gcvalues;
  2332. Cursor cursor;
  2333. Window parent;
  2334. int sw, sh;
  2335. if(!(xw.dpy = XOpenDisplay(NULL)))
  2336. die("Can't open display\n");
  2337. xw.scr = XDefaultScreen(xw.dpy);
  2338. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2339. /* font */
  2340. if(!FcInit())
  2341. die("Could not init fontconfig.\n");
  2342. usedfont = (opt_font == NULL)? font : opt_font;
  2343. xloadfonts(usedfont, 0);
  2344. /* colors */
  2345. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2346. xloadcols();
  2347. /* adjust fixed window geometry */
  2348. if(xw.isfixed) {
  2349. sw = DisplayWidth(xw.dpy, xw.scr);
  2350. sh = DisplayHeight(xw.dpy, xw.scr);
  2351. if(xw.fx < 0)
  2352. xw.fx = sw + xw.fx - xw.fw - 1;
  2353. if(xw.fy < 0)
  2354. xw.fy = sh + xw.fy - xw.fh - 1;
  2355. xw.h = xw.fh;
  2356. xw.w = xw.fw;
  2357. } else {
  2358. /* window - default size */
  2359. xw.h = 2 * borderpx + term.row * xw.ch;
  2360. xw.w = 2 * borderpx + term.col * xw.cw;
  2361. xw.fx = 0;
  2362. xw.fy = 0;
  2363. }
  2364. /* Events */
  2365. attrs.background_pixel = dc.col[defaultbg].pixel;
  2366. attrs.border_pixel = dc.col[defaultbg].pixel;
  2367. attrs.bit_gravity = NorthWestGravity;
  2368. attrs.event_mask = FocusChangeMask | KeyPressMask
  2369. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2370. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2371. attrs.colormap = xw.cmap;
  2372. parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
  2373. XRootWindow(xw.dpy, xw.scr);
  2374. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  2375. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2376. xw.vis,
  2377. CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
  2378. | CWColormap,
  2379. &attrs);
  2380. memset(&gcvalues, 0, sizeof(gcvalues));
  2381. gcvalues.graphics_exposures = False;
  2382. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  2383. &gcvalues);
  2384. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2385. DefaultDepth(xw.dpy, xw.scr));
  2386. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  2387. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2388. /* Xft rendering context */
  2389. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2390. /* input methods */
  2391. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2392. XSetLocaleModifiers("@im=local");
  2393. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2394. XSetLocaleModifiers("@im=");
  2395. if((xw.xim = XOpenIM(xw.dpy,
  2396. NULL, NULL, NULL)) == NULL) {
  2397. die("XOpenIM failed. Could not open input"
  2398. " device.\n");
  2399. }
  2400. }
  2401. }
  2402. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2403. | XIMStatusNothing, XNClientWindow, xw.win,
  2404. XNFocusWindow, xw.win, NULL);
  2405. if(xw.xic == NULL)
  2406. die("XCreateIC failed. Could not obtain input method.\n");
  2407. /* white cursor, black outline */
  2408. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2409. XDefineCursor(xw.dpy, xw.win, cursor);
  2410. XRecolorCursor(xw.dpy, cursor,
  2411. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2412. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2413. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2414. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2415. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2416. xresettitle();
  2417. XMapWindow(xw.dpy, xw.win);
  2418. xhints();
  2419. XSync(xw.dpy, 0);
  2420. }
  2421. void
  2422. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2423. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2424. width = charlen * xw.cw, xp, i;
  2425. int frp, frcflags;
  2426. int u8fl, u8fblen, u8cblen, doesexist;
  2427. char *u8c, *u8fs;
  2428. long u8char;
  2429. Font *font = &dc.font;
  2430. FcResult fcres;
  2431. FcPattern *fcpattern, *fontpattern;
  2432. FcFontSet *fcsets[] = { NULL };
  2433. FcCharSet *fccharset;
  2434. Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
  2435. *temp, revfg, revbg;
  2436. XRenderColor colfg, colbg;
  2437. frcflags = FRC_NORMAL;
  2438. if(base.mode & ATTR_BOLD) {
  2439. if(BETWEEN(base.fg, 0, 7)) {
  2440. /* basic system colors */
  2441. fg = &dc.col[base.fg + 8];
  2442. } else if(BETWEEN(base.fg, 16, 195)) {
  2443. /* 256 colors */
  2444. fg = &dc.col[base.fg + 36];
  2445. } else if(BETWEEN(base.fg, 232, 251)) {
  2446. /* greyscale */
  2447. fg = &dc.col[base.fg + 4];
  2448. }
  2449. /*
  2450. * Those ranges will not be brightened:
  2451. * 8 - 15 – bright system colors
  2452. * 196 - 231 – highest 256 color cube
  2453. * 252 - 255 – brightest colors in greyscale
  2454. */
  2455. font = &dc.bfont;
  2456. frcflags = FRC_BOLD;
  2457. }
  2458. if(base.mode & ATTR_ITALIC) {
  2459. font = &dc.ifont;
  2460. frcflags = FRC_ITALIC;
  2461. }
  2462. if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
  2463. font = &dc.ibfont;
  2464. frcflags = FRC_ITALICBOLD;
  2465. }
  2466. if(IS_SET(MODE_REVERSE)) {
  2467. if(fg == &dc.col[defaultfg]) {
  2468. fg = &dc.col[defaultbg];
  2469. } else {
  2470. colfg.red = ~fg->color.red;
  2471. colfg.green = ~fg->color.green;
  2472. colfg.blue = ~fg->color.blue;
  2473. colfg.alpha = fg->color.alpha;
  2474. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2475. fg = &revfg;
  2476. }
  2477. if(bg == &dc.col[defaultbg]) {
  2478. bg = &dc.col[defaultfg];
  2479. } else {
  2480. colbg.red = ~bg->color.red;
  2481. colbg.green = ~bg->color.green;
  2482. colbg.blue = ~bg->color.blue;
  2483. colbg.alpha = bg->color.alpha;
  2484. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
  2485. bg = &revbg;
  2486. }
  2487. }
  2488. if(base.mode & ATTR_REVERSE) {
  2489. temp = fg;
  2490. fg = bg;
  2491. bg = temp;
  2492. }
  2493. /* Intelligent cleaning up of the borders. */
  2494. if(x == 0) {
  2495. xclear(0, (y == 0)? 0 : winy, borderpx,
  2496. winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
  2497. }
  2498. if(x + charlen >= term.col) {
  2499. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2500. ((y >= term.row-1)? xw.h : (winy + xw.ch)));
  2501. }
  2502. if(y == 0)
  2503. xclear(winx, 0, winx + width, borderpx);
  2504. if(y == term.row-1)
  2505. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2506. /* Clean up the region we want to draw to. */
  2507. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  2508. fcsets[0] = font->set;
  2509. for(xp = winx; bytelen > 0;) {
  2510. /*
  2511. * Search for the range in the to be printed string of glyphs
  2512. * that are in the main font. Then print that range. If
  2513. * some glyph is found that is not in the font, do the
  2514. * fallback dance.
  2515. */
  2516. u8fs = s;
  2517. u8fblen = 0;
  2518. u8fl = 0;
  2519. for(;;) {
  2520. u8c = s;
  2521. u8cblen = utf8decode(s, &u8char);
  2522. s += u8cblen;
  2523. bytelen -= u8cblen;
  2524. doesexist = XftCharIndex(xw.dpy, font->match, u8char);
  2525. if(!doesexist || bytelen <= 0) {
  2526. if(bytelen <= 0) {
  2527. if(doesexist) {
  2528. u8fl++;
  2529. u8fblen += u8cblen;
  2530. }
  2531. }
  2532. if(u8fl > 0) {
  2533. XftDrawStringUtf8(xw.draw, fg,
  2534. font->match, xp,
  2535. winy + font->ascent,
  2536. (FcChar8 *)u8fs,
  2537. u8fblen);
  2538. xp += font->width * u8fl;
  2539. }
  2540. break;
  2541. }
  2542. u8fl++;
  2543. u8fblen += u8cblen;
  2544. }
  2545. if(doesexist)
  2546. break;
  2547. frp = frccur;
  2548. /* Search the font cache. */
  2549. for(i = 0; i < frclen; i++, frp--) {
  2550. if(frp <= 0)
  2551. frp = LEN(frc) - 1;
  2552. if(frc[frp].c == u8char
  2553. && frc[frp].flags == frcflags) {
  2554. break;
  2555. }
  2556. }
  2557. /* Nothing was found. */
  2558. if(i >= frclen) {
  2559. /*
  2560. * Nothing was found in the cache. Now use
  2561. * some dozen of Fontconfig calls to get the
  2562. * font for one single character.
  2563. */
  2564. fcpattern = FcPatternDuplicate(font->pattern);
  2565. fccharset = FcCharSetCreate();
  2566. FcCharSetAddChar(fccharset, u8char);
  2567. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  2568. fccharset);
  2569. FcPatternAddBool(fcpattern, FC_SCALABLE,
  2570. FcTrue);
  2571. FcConfigSubstitute(0, fcpattern,
  2572. FcMatchPattern);
  2573. FcDefaultSubstitute(fcpattern);
  2574. fontpattern = FcFontSetMatch(0, fcsets,
  2575. FcTrue, fcpattern, &fcres);
  2576. /*
  2577. * Overwrite or create the new cache entry
  2578. * entry.
  2579. */
  2580. frccur++;
  2581. frclen++;
  2582. if(frccur >= LEN(frc))
  2583. frccur = 0;
  2584. if(frclen > LEN(frc)) {
  2585. frclen = LEN(frc);
  2586. XftFontClose(xw.dpy, frc[frccur].font);
  2587. }
  2588. frc[frccur].font = XftFontOpenPattern(xw.dpy,
  2589. fontpattern);
  2590. frc[frccur].c = u8char;
  2591. frc[frccur].flags = frcflags;
  2592. FcPatternDestroy(fcpattern);
  2593. FcCharSetDestroy(fccharset);
  2594. frp = frccur;
  2595. }
  2596. XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
  2597. xp, winy + frc[frp].font->ascent,
  2598. (FcChar8 *)u8c, u8cblen);
  2599. xp += font->width;
  2600. }
  2601. /*
  2602. XftDrawStringUtf8(xw.draw, fg, font->set, winx,
  2603. winy + font->ascent, (FcChar8 *)s, bytelen);
  2604. */
  2605. if(base.mode & ATTR_UNDERLINE) {
  2606. XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
  2607. width, 1);
  2608. }
  2609. }
  2610. void
  2611. xdrawcursor(void) {
  2612. static int oldx = 0, oldy = 0;
  2613. int sl;
  2614. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
  2615. LIMIT(oldx, 0, term.col-1);
  2616. LIMIT(oldy, 0, term.row-1);
  2617. if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
  2618. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  2619. /* remove the old cursor */
  2620. if(term.line[oldy][oldx].state & GLYPH_SET) {
  2621. sl = utf8size(term.line[oldy][oldx].c);
  2622. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  2623. oldy, 1, sl);
  2624. } else {
  2625. xtermclear(oldx, oldy, oldx, oldy);
  2626. }
  2627. /* draw the new one */
  2628. if(!(IS_SET(MODE_HIDE))) {
  2629. if(!(xw.state & WIN_FOCUSED))
  2630. g.bg = defaultucs;
  2631. if(IS_SET(MODE_REVERSE))
  2632. g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
  2633. sl = utf8size(g.c);
  2634. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  2635. oldx = term.c.x, oldy = term.c.y;
  2636. }
  2637. }
  2638. void
  2639. xsettitle(char *p) {
  2640. XTextProperty prop;
  2641. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  2642. &prop);
  2643. XSetWMName(xw.dpy, xw.win, &prop);
  2644. }
  2645. void
  2646. xresettitle(void) {
  2647. xsettitle(opt_title ? opt_title : "st");
  2648. }
  2649. void
  2650. redraw(int timeout) {
  2651. struct timespec tv = {0, timeout * 1000};
  2652. tfulldirt();
  2653. draw();
  2654. if(timeout > 0) {
  2655. nanosleep(&tv, NULL);
  2656. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2657. }
  2658. }
  2659. void
  2660. draw(void) {
  2661. drawregion(0, 0, term.col, term.row);
  2662. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
  2663. xw.h, 0, 0);
  2664. XSetForeground(xw.dpy, dc.gc,
  2665. dc.col[IS_SET(MODE_REVERSE)?
  2666. defaultfg : defaultbg].pixel);
  2667. }
  2668. void
  2669. drawregion(int x1, int y1, int x2, int y2) {
  2670. int ic, ib, x, y, ox, sl;
  2671. Glyph base, new;
  2672. char buf[DRAW_BUF_SIZ];
  2673. bool ena_sel = sel.bx != -1;
  2674. if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
  2675. ena_sel = 0;
  2676. if(!(xw.state & WIN_VISIBLE))
  2677. return;
  2678. for(y = y1; y < y2; y++) {
  2679. if(!term.dirty[y])
  2680. continue;
  2681. xtermclear(0, y, term.col, y);
  2682. term.dirty[y] = 0;
  2683. base = term.line[y][0];
  2684. ic = ib = ox = 0;
  2685. for(x = x1; x < x2; x++) {
  2686. new = term.line[y][x];
  2687. if(ena_sel && *(new.c) && selected(x, y))
  2688. new.mode ^= ATTR_REVERSE;
  2689. if(ib > 0 && (!(new.state & GLYPH_SET)
  2690. || ATTRCMP(base, new)
  2691. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  2692. xdraws(buf, base, ox, y, ic, ib);
  2693. ic = ib = 0;
  2694. }
  2695. if(new.state & GLYPH_SET) {
  2696. if(ib == 0) {
  2697. ox = x;
  2698. base = new;
  2699. }
  2700. sl = utf8size(new.c);
  2701. memcpy(buf+ib, new.c, sl);
  2702. ib += sl;
  2703. ++ic;
  2704. }
  2705. }
  2706. if(ib > 0)
  2707. xdraws(buf, base, ox, y, ic, ib);
  2708. }
  2709. xdrawcursor();
  2710. }
  2711. void
  2712. expose(XEvent *ev) {
  2713. XExposeEvent *e = &ev->xexpose;
  2714. if(xw.state & WIN_REDRAW) {
  2715. if(!e->count)
  2716. xw.state &= ~WIN_REDRAW;
  2717. }
  2718. redraw(0);
  2719. }
  2720. void
  2721. visibility(XEvent *ev) {
  2722. XVisibilityEvent *e = &ev->xvisibility;
  2723. if(e->state == VisibilityFullyObscured) {
  2724. xw.state &= ~WIN_VISIBLE;
  2725. } else if(!(xw.state & WIN_VISIBLE)) {
  2726. /* need a full redraw for next Expose, not just a buf copy */
  2727. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2728. }
  2729. }
  2730. void
  2731. unmap(XEvent *ev) {
  2732. xw.state &= ~WIN_VISIBLE;
  2733. }
  2734. void
  2735. xseturgency(int add) {
  2736. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2737. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2738. XSetWMHints(xw.dpy, xw.win, h);
  2739. XFree(h);
  2740. }
  2741. void
  2742. focus(XEvent *ev) {
  2743. XFocusChangeEvent *e = &ev->xfocus;
  2744. if(e->mode == NotifyGrab)
  2745. return;
  2746. if(ev->type == FocusIn) {
  2747. XSetICFocus(xw.xic);
  2748. xw.state |= WIN_FOCUSED;
  2749. xseturgency(0);
  2750. } else {
  2751. XUnsetICFocus(xw.xic);
  2752. xw.state &= ~WIN_FOCUSED;
  2753. }
  2754. }
  2755. inline bool
  2756. match(uint mask, uint state) {
  2757. state &= ~(ignoremod);
  2758. if(mask == XK_NO_MOD && state)
  2759. return false;
  2760. if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
  2761. return false;
  2762. if((state & mask) != state)
  2763. return false;
  2764. return true;
  2765. }
  2766. void
  2767. numlock(const Arg *dummy) {
  2768. term.numlock ^= 1;
  2769. }
  2770. char*
  2771. kmap(KeySym k, uint state) {
  2772. uint mask;
  2773. Key *kp;
  2774. int i;
  2775. /* Check for mapped keys out of X11 function keys. */
  2776. for(i = 0; i < LEN(mappedkeys); i++) {
  2777. if(mappedkeys[i] == k)
  2778. break;
  2779. }
  2780. if(i == LEN(mappedkeys)) {
  2781. if((k & 0xFFFF) < 0xFD00)
  2782. return NULL;
  2783. }
  2784. for(kp = key; kp < key + LEN(key); kp++) {
  2785. mask = kp->mask;
  2786. if(kp->k != k)
  2787. continue;
  2788. if(!match(mask, state))
  2789. continue;
  2790. if(kp->appkey > 0) {
  2791. if(!IS_SET(MODE_APPKEYPAD))
  2792. continue;
  2793. if(term.numlock && kp->appkey == 2)
  2794. continue;
  2795. } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
  2796. continue;
  2797. }
  2798. if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
  2799. (kp->appcursor > 0
  2800. && !IS_SET(MODE_APPCURSOR))) {
  2801. continue;
  2802. }
  2803. if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
  2804. (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
  2805. continue;
  2806. }
  2807. return kp->s;
  2808. }
  2809. return NULL;
  2810. }
  2811. void
  2812. kpress(XEvent *ev) {
  2813. XKeyEvent *e = &ev->xkey;
  2814. KeySym ksym;
  2815. char xstr[31], buf[32], *customkey, *cp = buf;
  2816. int len;
  2817. Status status;
  2818. Shortcut *bp;
  2819. if(IS_SET(MODE_KBDLOCK))
  2820. return;
  2821. len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
  2822. e->state &= ~Mod2Mask;
  2823. /* 1. shortcuts */
  2824. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  2825. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  2826. bp->func(&(bp->arg));
  2827. return;
  2828. }
  2829. }
  2830. /* 2. custom keys from config.h */
  2831. if((customkey = kmap(ksym, e->state))) {
  2832. len = strlen(customkey);
  2833. memcpy(buf, customkey, len);
  2834. /* 2. hardcoded (overrides X lookup) */
  2835. } else {
  2836. if(len == 0)
  2837. return;
  2838. if(len == 1 && e->state & Mod1Mask)
  2839. *cp++ = '\033';
  2840. memcpy(cp, xstr, len);
  2841. len = cp - buf + len;
  2842. }
  2843. ttywrite(buf, len);
  2844. if(IS_SET(MODE_ECHO))
  2845. techo(buf, len);
  2846. }
  2847. void
  2848. cmessage(XEvent *e) {
  2849. /*
  2850. * See xembed specs
  2851. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  2852. */
  2853. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  2854. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  2855. xw.state |= WIN_FOCUSED;
  2856. xseturgency(0);
  2857. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  2858. xw.state &= ~WIN_FOCUSED;
  2859. }
  2860. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  2861. /* Send SIGHUP to shell */
  2862. kill(pid, SIGHUP);
  2863. exit(EXIT_SUCCESS);
  2864. }
  2865. }
  2866. void
  2867. cresize(int width, int height) {
  2868. int col, row;
  2869. if(width != 0)
  2870. xw.w = width;
  2871. if(height != 0)
  2872. xw.h = height;
  2873. col = (xw.w - 2 * borderpx) / xw.cw;
  2874. row = (xw.h - 2 * borderpx) / xw.ch;
  2875. tresize(col, row);
  2876. xresize(col, row);
  2877. ttyresize();
  2878. }
  2879. void
  2880. resize(XEvent *e) {
  2881. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  2882. return;
  2883. cresize(e->xconfigure.width, e->xconfigure.height);
  2884. }
  2885. void
  2886. run(void) {
  2887. XEvent ev;
  2888. fd_set rfd;
  2889. int xfd = XConnectionNumber(xw.dpy), xev;
  2890. struct timeval drawtimeout, *tv = NULL, now, last;
  2891. gettimeofday(&last, NULL);
  2892. for(xev = actionfps;;) {
  2893. FD_ZERO(&rfd);
  2894. FD_SET(cmdfd, &rfd);
  2895. FD_SET(xfd, &rfd);
  2896. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  2897. if(errno == EINTR)
  2898. continue;
  2899. die("select failed: %s\n", SERRNO);
  2900. }
  2901. gettimeofday(&now, NULL);
  2902. drawtimeout.tv_sec = 0;
  2903. drawtimeout.tv_usec = (1000/xfps) * 1000;
  2904. tv = &drawtimeout;
  2905. if(FD_ISSET(cmdfd, &rfd))
  2906. ttyread();
  2907. if(FD_ISSET(xfd, &rfd))
  2908. xev = actionfps;
  2909. if(TIMEDIFF(now, last) > \
  2910. (xev ? (1000/xfps) : (1000/actionfps))) {
  2911. while(XPending(xw.dpy)) {
  2912. XNextEvent(xw.dpy, &ev);
  2913. if(XFilterEvent(&ev, None))
  2914. continue;
  2915. if(handler[ev.type])
  2916. (handler[ev.type])(&ev);
  2917. }
  2918. draw();
  2919. XFlush(xw.dpy);
  2920. last = now;
  2921. if(xev && !FD_ISSET(xfd, &rfd))
  2922. xev--;
  2923. if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
  2924. tv = NULL;
  2925. }
  2926. }
  2927. }
  2928. int
  2929. main(int argc, char *argv[]) {
  2930. int i, bitm, xr, yr;
  2931. uint wr, hr;
  2932. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  2933. xw.isfixed = False;
  2934. for(i = 1; i < argc; i++) {
  2935. switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
  2936. case 'c':
  2937. if(++i < argc)
  2938. opt_class = argv[i];
  2939. break;
  2940. case 'e':
  2941. /* eat all remaining arguments */
  2942. if(++i < argc)
  2943. opt_cmd = &argv[i];
  2944. goto run;
  2945. case 'f':
  2946. if(++i < argc)
  2947. opt_font = argv[i];
  2948. break;
  2949. case 'g':
  2950. if(++i >= argc)
  2951. break;
  2952. bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
  2953. if(bitm & XValue)
  2954. xw.fx = xr;
  2955. if(bitm & YValue)
  2956. xw.fy = yr;
  2957. if(bitm & WidthValue)
  2958. xw.fw = (int)wr;
  2959. if(bitm & HeightValue)
  2960. xw.fh = (int)hr;
  2961. if(bitm & XNegative && xw.fx == 0)
  2962. xw.fx = -1;
  2963. if(bitm & XNegative && xw.fy == 0)
  2964. xw.fy = -1;
  2965. if(xw.fh != 0 && xw.fw != 0)
  2966. xw.isfixed = True;
  2967. break;
  2968. case 'o':
  2969. if(++i < argc)
  2970. opt_io = argv[i];
  2971. break;
  2972. case 't':
  2973. if(++i < argc)
  2974. opt_title = argv[i];
  2975. break;
  2976. case 'v':
  2977. default:
  2978. die(USAGE);
  2979. case 'w':
  2980. if(++i < argc)
  2981. opt_embed = argv[i];
  2982. break;
  2983. }
  2984. }
  2985. run:
  2986. setlocale(LC_CTYPE, "");
  2987. XSetLocaleModifiers("");
  2988. tnew(80, 24);
  2989. xinit();
  2990. ttynew();
  2991. selinit();
  2992. run();
  2993. return 0;
  2994. }