st.c 80 KB

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