st.c 80 KB

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